U
    +if                    @  s  d Z ddlmZ ddlmZ ddlmZmZ ddlZddl	m
Z
 ddlmZ ddlZddlZddlmZ dd	lmZmZmZmZmZmZmZmZmZmZ dd
lmZ ddlZddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZI ddlJmKZKmLZLmMZM ddlNmOZO ddlPmQ  mRZS ddlTmUZU ddlVmWZWmXZXmYZYmZZZ ddl[m\Z\ ddl]m^Z^ ddl_m`Z` ddlambZbmcZc ddldmeZemfZfmgZg er(ddlhmiZimjZj dZkdZldZmG d d! d!ZnG d"d# d#ZoG d$d% d%ZpG d&d' d'epZqd%d(d)d*Zrd+d(d,d-Zsd+d(d.d/ZtG d0d1 d1ZuG d2d3 d3Zvdd4d5d6d6d7d8d9Zwedd5d6d:d;d<ZxddAdBdCd4dDdEd4d4dFdDdGdHdIdJZyG dKdL dLZzG dMdN dNezZ{G dOdP dPezZ|G dQdR dRezZ}G dSdT dTezZ~dUdGdVdWdXZdYdZd[d\d]Zdd_d4d4d`dadbZdd_d4d6d4dcdddeZddZd4d6dfdgdhdiZdjd6d6dkdldmZG dndo doe}ZG dpdq dqezZddsd4dZdfdtdudvZddGd4dDdwdGdxdydzZdd{d4dGd|d}d~Zd4d4dddZddd4dGdddZddZdddZG dd dZdddZddddZddAdddddZddGddddZdS )z
Internal module for formatting output data in csv, html, xml,
and latex files. This module also applies to display formatting.
    )annotations)contextmanager)
QUOTE_NONEQUOTE_NONNUMERICN)partial)StringIO)get_terminal_size)
IOTYPE_CHECKINGAnyCallableHashableIterableListMappingSequencecast)east_asian_width)
get_option
set_option)lib)NA)NaT	Timedelta	TimestampiNaT)NaTType)
	ArrayLikeColspaceArgTypeColspaceTypeCompressionOptionsFilePathFloatFormatTypeFormattersType
IndexLabelStorageOptionsWriteBuffer)is_categorical_dtypeis_complex_dtypeis_datetime64_dtypeis_datetime64tz_dtypeis_extension_array_dtypeis_floatis_float_dtype
is_integeris_integer_dtypeis_list_likeis_numeric_dtype	is_scalaris_timedelta64_dtype)isnanotna)CategoricalDatetimeArrayTimedeltaArray)PandasObject)extract_array)Index
MultiIndexPeriodIndexensure_index)DatetimeIndex)TimedeltaIndex)concat)check_parent_directorystringify_path)adjoinjustifypprint_thing)	DataFrameSeriesa	  
        Parameters
        ----------
        buf : str, Path or StringIO-like, optional, default None
            Buffer to write to. If None, the output is returned as a string.
        columns : sequence, optional, default None
            The subset of columns to write. Writes all columns by default.
        col_space : %(col_space_type)s, optional
            %(col_space)s.
        header : %(header_type)s, optional
            %(header)s.
        index : bool, optional, default True
            Whether to print index (row) labels.
        na_rep : str, optional, default 'NaN'
            String representation of ``NaN`` to use.
        formatters : list, tuple or dict of one-param. functions, optional
            Formatter functions to apply to columns' elements by position or
            name.
            The result of each function must be a unicode string.
            List/tuple must be of length equal to the number of columns.
        float_format : one-parameter function, optional, default None
            Formatter function to apply to columns' elements if they are
            floats. This function must return a unicode string and will be
            applied only to the non-``NaN`` elements, with ``NaN`` being
            handled by ``na_rep``.

            .. versionchanged:: 1.2.0

        sparsify : bool, optional, default True
            Set to False for a DataFrame with a hierarchical index to print
            every multiindex key at each row.
        index_names : bool, optional, default True
            Prints the names of the indexes.
        justify : str, default None
            How to justify the column labels. If None uses the option from
            the print configuration (controlled by set_option), 'right' out
            of the box. Valid values are

            * left
            * right
            * center
            * justify
            * justify-all
            * start
            * end
            * inherit
            * match-parent
            * initial
            * unset.
        max_rows : int, optional
            Maximum number of rows to display in the console.
        max_cols : int, optional
            Maximum number of columns to display in the console.
        show_dimensions : bool, default False
            Display DataFrame dimensions (number of rows by number of columns).
        decimal : str, default '.'
            Character recognized as decimal separator, e.g. ',' in Europe.
    )leftrightcenterrE   zjustify-allstartendinheritzmatch-parentinitialunsetz
        Returns
        -------
        str or None
            If buf is None, returns the result as a string. Otherwise returns
            None.
    c                   @  sN   e Zd Zdddddddd	d
ZddddZddddZddddZdS )CategoricalFormatterNTNaNr6   IO[str] | Noneboolstr)categoricalbuflengthna_repfooterc                 C  s8   || _ |d k	r|ntd| _|| _|| _|| _t| _d S N )rV   r   rW   rY   rX   rZ   r   quoting)selfrV   rW   rX   rY   rZ    r_   K/home/mars/bis/venv/lib/python3.8/site-packages/pandas/io/formats/format.py__init__   s    zCategoricalFormatter.__init__returnc                 C  sP   d}| j r*|r|d7 }|dt| j 7 }| j }|r@|d7 }||7 }t|S )Nr\   , Length: 
)rX   lenrV   _repr_categories_inforU   )r^   rZ   
level_infor_   r_   r`   _get_footer   s    
z CategoricalFormatter._get_footer	list[str]c                 C  s   t | j d d | j| jdS )N)float_formatrY   r]   )format_arrayrV   _internal_get_valuesrY   r]   r^   r_   r_   r`   _get_formatted_values   s    z*CategoricalFormatter._get_formatted_valuesc                 C  s|   | j }t|dkr$| jr |  S dS |  }dd |D }d|}d| d g}| jrn|  }|rn|| td|S )	Nr   r\   c                 S  s   g | ]}|  qS r_   )strip.0ir_   r_   r`   
<listcomp>   s     z2CategoricalFormatter.to_string.<locals>.<listcomp>rd   []rf   )rV   rg   rZ   rj   rp   joinappendrU   )r^   rV   
fmt_valuesvaluesresultrZ   r_   r_   r`   	to_string   s    

zCategoricalFormatter.to_string)NTrR   T)__name__
__module____qualname__ra   rj   rp   r}   r_   r_   r_   r`   rQ      s       	rQ   c                   @  sv   e Zd Zddddddd	dd
ddddddZddddZd	dddZddddZddddZd	dddZdS )SeriesFormatterNTrR   FrH   rS   
bool | strrT   rU   
str | None
int | None)seriesrW   rX   headerindexrY   namerl   dtypemax_rowsmin_rowsc                 C  st   || _ |d k	r|nt | _|| _|| _|| _|| _|| _|
| _|| _	|d krTt
d}|| _|	| _t | _|   d S )Ndisplay.float_format)r   r   rW   r   rY   r   rX   r   r   r   r   rl   r   get_adjustmentadj_chk_truncate)r^   r   rW   rX   r   r   rY   r   rl   r   r   r   r_   r_   r`   ra     s    zSeriesFormatter.__init__Nonerb   c                 C  s   |  | j }| j}|o t| j|k}| j}|rtt|}|rDt||}|dkr`|}|jd | }n*|d }t|jd | |j| d  f}|| _	nd | _	|| _
|| _d S )N      )r   r   rg   r   r   intminilocrA   
tr_row_num	tr_seriesis_truncated_vertically)r^   r   r   r   r   row_numr_   r_   r`   r   '  s$    

"zSeriesFormatter._chk_truncatec                 C  sB  | j j}d}t| j jdd d k	rLt| j jtttfs8t|d| j jj	 7 }| jdk	r|d k	r|rj|d7 }t
|dd}|d| 7 }| jd	ks| jd
kr| jr|r|d7 }|dt| j  7 }| jdk	r
| jd k	r
t| jjdd }|r
|r|d7 }|dt
| 7 }t| jjr:| jj }|r2|d7 }||7 }t|S )Nr\   freqzFreq: Frd   	rf   )escape_charszName: Ttruncatere   r   zdtype: rf   )r   r   getattrr   
isinstancer?   r=   r@   AssertionErrorZfreqstrrF   rX   r   rg   r   r   r'   _valuesrh   rU   )r^   r   rZ   Zseries_nameZ
dtype_nameri   r_   r_   r`   rj   B  sB     
zSeriesFormatter._get_footerztuple[list[str], bool]c                 C  sR   | j j}t|tr4tdd |jD }|jdd}n|jd k	}|jdd}||fS )Nc                 s  s   | ]
}|V  qd S Nr_   rs   r   r_   r_   r`   	<genexpr>o  s     z7SeriesFormatter._get_formatted_index.<locals>.<genexpr>T)names)r   )r   r   r   r<   anyr   formatr   )r^   r   have_header	fmt_indexr_   r_   r`   _get_formatted_indexk  s    

z$SeriesFormatter._get_formatted_indexrk   c                 C  s   t | jjd | j| j| jdS )N)rl   rY   leading_space)rm   r   r   rl   rY   r   ro   r_   r_   r`   rp   v  s    z%SeriesFormatter._get_formatted_valuesc                 C  s.  | j }|  }t|dkr2t| jj d| dS |  \}}|  }| jrd}| j	}t
t|}| j||d  }|dkrd}	nd}	| jj|	g|dd	d }	||| |	 ||d d
 | jr| jjd|dd  |g }
n| jd|}
| jr|r|d d |
 }
|r |
d| 7 }
td
|
S )Nr   z([], )r      ...z..rK   moder\   rf   )r   )r   rj   rg   typer   r~   r   rp   r   r   r   r   r   rE   insertr   rD   r   rU   rx   )r^   r   rZ   r   r   rz   Zn_header_rowsr   widthZdot_strr|   r_   r_   r`   r}     s2    
zSeriesFormatter.to_string)
NTTTrR   FNTNN)	r~   r   r   ra   r   rj   r   rp   r}   r_   r_   r_   r`   r     s              $ )	r   c                   @  sJ   e Zd Zdd ZdddddZdd	ddd
dddZdddddZdS )TextAdjustmentc                 C  s   t d| _d S )Nzdisplay.encoding)r   encodingro   r_   r_   r`   ra     s    zTextAdjustment.__init__rU   r   textrc   c                 C  s   t |S r   rg   r^   r   r_   r_   r`   rg     s    zTextAdjustment.lenrJ   r   rk   textsmax_lenr   rc   c                 C  s   t |||dS )Nr   )rE   r^   r   r   r   r_   r_   r`   rE     s    zTextAdjustment.justify)spacerc   c                 O  s   t |f|| j| jd|S )N)ZstrlenZjustfunc)rD   rg   rE   )r^   r   listskwargsr_   r_   r`   rD     s    zTextAdjustment.adjoinN)rJ   )r~   r   r   ra   rg   rE   rD   r_   r_   r_   r`   r     s   r   c                      sB   e Zd Z fddZdddddZdd	ddd
dddZ  ZS )EastAsianTextAdjustmentc                   s6   t    tdrd| _nd| _dddddd| _d S )Nz!display.unicode.ambiguous_as_wider   r   )ZNaNWFH)superra   r   ambiguous_width_EAW_MAPro   	__class__r_   r`   ra     s
    
z EastAsianTextAdjustment.__init__rU   r   r   c                   s(   t |tst|S t fdd|D S )zN
        Calculate display width considering unicode East Asian Width
        c                 3  s"   | ]} j t| jV  qd S r   )r   getr   r   )rs   cro   r_   r`   r     s    z.EastAsianTextAdjustment.len.<locals>.<genexpr>)r   rU   rg   sumr   r_   ro   r`   rg     s
    
zEastAsianTextAdjustment.lenrJ   zIterable[str]rk   r   c                   sX   fdd |dkr( fdd|D S |dkrB fdd|D S  fdd|D S d S )	Nc                   s     |  t |  S r   r   )t)r   r^   r_   r`   _get_pad  s    z1EastAsianTextAdjustment.justify.<locals>._get_padrI   c                   s   g | ]}|  |qS r_   )ljustrs   xr   r_   r`   ru     s     z3EastAsianTextAdjustment.justify.<locals>.<listcomp>rK   c                   s   g | ]}|  |qS r_   )rK   r   r   r_   r`   ru     s     c                   s   g | ]}|  |qS r_   )rjustr   r   r_   r`   ru     s     r_   r   r_   )r   r   r^   r`   rE     s    zEastAsianTextAdjustment.justify)rJ   )r~   r   r   ra   rg   rE   __classcell__r_   r_   r   r`   r     s    r   rb   c                  C  s   t d} | rt S t S d S )Nz display.unicode.east_asian_width)r   r   r   )Zuse_east_asian_widthr_   r_   r`   r     s    r   zdict[str, Any]c                  C  sL   ddl m}  tdr"|  \}}nd}tdtdtdtdtd	|d
S )a  Get the parameters used to repr(dataFrame) calls using DataFrame.to_string.

    Supplying these parameters to DataFrame.to_string is equivalent to calling
    ``repr(DataFrame)``. This is useful if you want to adjust the repr output.

    .. versionadded:: 1.4.0

    Example
    -------
    >>> import pandas as pd
    >>>
    >>> df = pd.DataFrame([[1, 2], [3, 4]])
    >>> repr_params = pd.io.formats.format.get_dataframe_repr_params()
    >>> repr(df) == df.to_string(**repr_params)
    True
    r   )consolezdisplay.expand_frame_reprNdisplay.max_rowsdisplay.min_rowszdisplay.max_columnsdisplay.max_colwidthdisplay.show_dimensions)r   r   max_colsZmax_colwidthshow_dimensions
line_width)Zpandas.io.formatsr   r   Zget_console_size)r   r   _r_   r_   r`   get_dataframe_repr_params  s    r   c                  C  sN   t  \} }tddkr|ntd}tddkr2|ntd}dd||tddS )a  Get the parameters used to repr(Series) calls using Series.to_string.

    Supplying these parameters to Series.to_string is equivalent to calling
    ``repr(series)``. This is useful if you want to adjust the series repr output.

    .. versionadded:: 1.4.0

    Example
    -------
    >>> import pandas as pd
    >>>
    >>> ser = pd.Series([1, 2, 3, 4])
    >>> repr_params = pd.io.formats.format.get_series_repr_params()
    >>> repr(ser) == ser.to_string(**repr_params)
    True
    r   r   r   Tr   )r   r   r   r   rX   )r   r   )r   heightr   r   r_   r_   r`   get_series_repr_params  s    


r   c                   @  sV  e Zd ZdZerendZeee 7 Zdidd	d
ddddddddddddddddddZddddZeddddZ	eddddZ
edddd Zeddd!d"Zeddd#d$Zeddd%d&Zeddd'd(Zeddd)d*Zeddd+d,Zed-dd.d/Zddd0d1d2Zdd3d4d5d6Zddd7d8d9Zd	d:d;d<d=Zd
d>d?d@dAZdddBdCZdddDdEZdddFdGdHZdddIdJZdddKdLZdddMdNZd-ddOdPZdQddRdSZdQddTdUZ dQddVdWZ!dddXdYZ"d-dZd[d\d]Z#d^d_d[d`daZ$dddbdcddZ%ddZdbdedfZ&dZddgdhZ'dS )jDataFrameFormatterz;Class for processing dataframe formatting options and data.r\   NTrR   F.rG   zSequence[str] | NonezColspaceArgType | Nonezbool | Sequence[str]rT   rU   zFormattersType | Noner   FloatFormatType | Nonebool | Noner   r   )framecolumns	col_spacer   r   rY   
formattersrE   rl   sparsifyindex_namesr   r   r   r   decimal	bold_rowsescapec                 C  s   || _ | || _| || _|| _|| _|| _| || _	| 
|| _|	| _| |
| _|| _|| _|| _|| _|| _|| _|| _|| _|  | _|  | _| j | _|   t | _d S r   )r   _initialize_columnsr   _initialize_colspacer   r   r   rY   _initialize_formattersr   _initialize_justifyrE   rl   _initialize_sparsifyr   show_index_namesr   r   r   r   r   r   r   _calc_max_cols_fittedmax_cols_fitted_calc_max_rows_fittedmax_rows_fittedtr_framer   r   r   )r^   r   r   r   r   r   rY   r   rE   rl   r   r   r   r   r   r   r   r   r   r_   r_   r`   ra   0  s.    

zDataFrameFormatter.__init__zlist[list[str]]rb   c                 C  s*   |   }| jr&| | j}|d| |S )zP
        Render a DataFrame to a list of columns (as lists of strings).
        r   )_get_strcols_without_indexr   r   r   r   )r^   strcolsZ	str_indexr_   r_   r`   get_strcols_  s
    zDataFrameFormatter.get_strcolsc                 C  s   | j dkp| j dko| jS )NTr   )r   is_truncatedro   r_   r_   r`   should_show_dimensionsk  s    
z)DataFrameFormatter.should_show_dimensionsc                 C  s   t | jp| jS r   )rT   is_truncated_horizontallyr   ro   r_   r_   r`   r   q  s    zDataFrameFormatter.is_truncatedc                 C  s   t | jot| j| jkS r   )rT   r   rg   r   ro   r_   r_   r`   r  u  s    z,DataFrameFormatter.is_truncated_horizontallyc                 C  s   t | jot| j| jkS r   )rT   r   rg   r   ro   r_   r_   r`   r   y  s    z*DataFrameFormatter.is_truncated_verticallyc                 C  s    dt | j dt | jj dS )Nz

[z rows x z	 columns])rg   r   r   ro   r_   r_   r`   dimensions_info}  s    z"DataFrameFormatter.dimensions_infoc                 C  s   t | jjS r   )
_has_namesr   r   ro   r_   r_   r`   has_index_names  s    z"DataFrameFormatter.has_index_namesc                 C  s   t | jjS r   )r  r   r   ro   r_   r_   r`   has_column_names  s    z#DataFrameFormatter.has_column_namesc                 C  s   t | j| j| jfS r   )allr  r   r   ro   r_   r_   r`   show_row_idx_names  s    z%DataFrameFormatter.show_row_idx_namesc                 C  s   t | j| j| jfS r   )r  r  r   r   ro   r_   r_   r`   show_col_idx_names  s    z%DataFrameFormatter.show_col_idx_namesr   c                 C  s   t | jpt| jt| jS r   )r   r   rg   r   ro   r_   r_   r`   max_rows_displayed  s    z%DataFrameFormatter.max_rows_displayed)r   rc   c                 C  s   |d krt dS |S )Nzdisplay.multi_sparser   )r^   r   r_   r_   r`   r     s    z'DataFrameFormatter._initialize_sparsifyr#   )r   rc   c                 C  sT   |d kri S t | jjt |ks*t|tr.|S tdt | dt | jj dd S )NzFormatters length(+) should match DataFrame number of columns(r   )rg   r   r   r   dict
ValueError)r^   r   r_   r_   r`   r     s    z)DataFrameFormatter._initialize_formatters)rE   rc   c                 C  s   |d krt dS |S d S )Nzdisplay.colheader_justifyr
  )r^   rE   r_   r_   r`   r     s    z&DataFrameFormatter._initialize_justifyr;   )r   rc   c                 C  s,   |d k	r t |}| j| | _|S | jjS d S r   )r>   r   r   )r^   r   colsr_   r_   r`   r     s
    z&DataFrameFormatter._initialize_columnsr   )r   rc   c                   s    d kri }nt  ttfrBd i}| fdd| jjD  nt  tr  D ]&}|| jjkrT|dkrTtd| qT }nHt	| jjt	 krtdt	  dt	| jj dt
t| jj }|S )Nr\   c                   s   i | ]
}| qS r_   r_   )rs   columnr   r_   r`   
<dictcomp>  s      z;DataFrameFormatter._initialize_colspace.<locals>.<dictcomp>z,Col_space is defined for an unknown column: zCol_space length(r  r   )r   r   rU   updater   r   r   keysr  rg   r  zip)r^   r   r|   r  r_   r  r`   r     s$    
z'DataFrameFormatter._initialize_colspacec                 C  s0   |   s| jS t \}}| |r&|S | jS dS )z%Number of columns fitting the screen.N)_is_in_terminalr   r   _is_screen_narrow)r^   r   r   r_   r_   r`   r     s    

z(DataFrameFormatter._calc_max_cols_fittedc                 C  sP   |   r@t \}}| jdkr(||   S | |r8|}qF| j}n| j}| |S )z,Number of rows with data fitting the screen.r   )r  r   r   _get_number_of_auxillary_rows_is_screen_short_adjust_max_rows)r^   r   r   r   r_   r_   r`   r     s    


z(DataFrameFormatter._calc_max_rows_fitted)r   rc   c                 C  s(   |r$t | j|kr$| jr$t| j|}|S )zAdjust max_rows using display logic.

        See description here:
        https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options

        GH #37359
        )rg   r   r   r   )r^   r   r_   r_   r`   r    s    z#DataFrameFormatter._adjust_max_rowsc                 C  s   t | jdkp| jdkS )z/Check if the output is to be shown in terminal.r   )rT   r   r   ro   r_   r_   r`   r    s    z"DataFrameFormatter._is_in_terminalc                 C  s   t | jdkot| jj|kS Nr   )rT   r   rg   r   r   )r^   	max_widthr_   r_   r`   r    s    z$DataFrameFormatter._is_screen_narrowc                 C  s   t | jdkot| j|kS r  )rT   r   rg   r   )r^   
max_heightr_   r_   r`   r     s    z#DataFrameFormatter._is_screen_shortc                 C  s:   d}d}|| }| j r(|t| j 7 }| jr6|d7 }|S )z?Get number of rows occupied by prompt, dots and dimension info.r   )r   rg   r  
splitlinesr   )r^   Zdot_rowZ
prompt_rowZnum_rowsr_   r_   r`   r    s    z0DataFrameFormatter._get_number_of_auxillary_rowsr   c                 C  s    | j r|   | jr|   dS )zY
        Check whether the frame should be truncated. If so, slice the frame up.
        N)r  _truncate_horizontallyr   _truncate_verticallyro   r_   r_   r`   r     s    zDataFrameFormatter.truncatec                 C  s   | j dk	st| j d }|dkr| jjddd|f }| jjdd| df }t||fdd| _t| jttfr| jd| | j| d | _n&t	t
| j}| jjddd|f | _|| _dS )zRemove columns, which are not to be displayed and adjust formatters.

        Attributes affected:
            - tr_frame
            - formatters
            - tr_col_num
        Nr   r   Zaxis)r   r   r   r   rA   r   r   listtupler   r   r   Z
tr_col_num)r^   Zcol_numrI   rJ   r_   r_   r`   r    s    
z)DataFrameFormatter._truncate_horizontallyc                 C  s   | j dk	st| j d }|dkrb| jjd|ddf }| jj| dddf }t||f| _n&tt| j}| jjd|ddf | _|| _dS )zRemove rows, which are not to be displayed.

        Attributes affected:
            - tr_frame
            - tr_row_num
        Nr   r   )	r   r   r   r   rA   r   r   r   r   )r^   r   headtailr_   r_   r`   r  5  s    
z'DataFrameFormatter._truncate_verticallyc           
   	     s  g }t  jsb jsbt jD ]>\}} |}t| jt j	|d j
d}|| q|S t  jrttt  j _t jt jkrtdt j dt j ddd  jD }n  j} jr|D ]}|d qt jD ]\}}|| }tt j	|df fd	d
|D  } |}t| j| j
d}tt fdd
|D |}	 j
j||	 jd}|||  q|S )Nr   )stringsrE   minimumr   zWriting z cols but got z aliasesc                 S  s   g | ]
}|gqS r_   r_   )rs   labelr_   r_   r`   ru   ^  s     zADataFrameFormatter._get_strcols_without_index.<locals>.<listcomp>r\   c                 3  s   | ]} j |V  qd S r   r   rg   r   ro   r_   r`   r   i  s     z@DataFrameFormatter._get_strcols_without_index.<locals>.<genexpr>)r&  r   c                 3  s   | ]} j |V  qd S r   r(  r   ro   r_   r`   r   p  s     r   )r0   r   	enumerater   
format_col_make_fixed_widthrE   r   r   r   r   ry   r   r   rU   rg   r   r  _get_formatted_column_labelsr  max)
r^   r   rt   r   rz   str_columnsr   ZcheaderZheader_colwidthr   r_   ro   r`   r   G  sR    


   z-DataFrameFormatter._get_strcols_without_indexrk   )rt   rc   c              	   C  sL   | j }| |}t|jd d |f j|| j| j| j|j	| | j
| jdS )N)rl   rY   r   r   r   )r   _get_formatterrm   r   r   rl   rY   r   r   r   r   r   )r^   rt   r   	formatterr_   r_   r`   r*  v  s    
zDataFrameFormatter.format_col	str | intCallable | Nonec                 C  s`   t | jttfr2t|r,tt|}| j| S d S n*t|rN|| jkrN| j| }| j|d S d S r   )	r   r   r!  r"  r.   r   r   r   r   )r^   rt   r_   r_   r`   r/    s    


z!DataFrameFormatter._get_formatter)r   rc   c                   s   ddl m} |j}t|tr|jddd}tt| }jj	j
}tdd |jD tt|tt|  fddttfd	d|D  }jrt|r||}d
d t| D }n<| }jj	}tt|tt|  fddt|D }|S )Nr   )sparsify_labelsF)r   rD   c                 s  s   | ]}|j V  qd S r   )Zis_floating)rs   levelr_   r_   r`   r     s     zBDataFrameFormatter._get_formatted_column_labels.<locals>.<genexpr>c                   s"   |j kr |  rsd| S |S )N )r   )r   y)need_leadsprestrict_formattingr^   r_   r`   space_format  s    zEDataFrameFormatter._get_formatted_column_labels.<locals>.space_formatc                 3  s"   | ]  fd d D V  qdS )c                   s   g | ]} |qS r_   r_   )rs   r6  )r9  r   r_   r`   ru     s     zMDataFrameFormatter._get_formatted_column_labels.<locals>.<genexpr>.<listcomp>Nr_   )rs   )r9  r   r`   r     s     c                 S  s   g | ]}t |qS r_   )r!  r   r_   r_   r`   ru     s     zCDataFrameFormatter._get_formatted_column_labels.<locals>.<listcomp>c                   s0   g | ](\}} |s& | r&d | n|gqS )r5  )r/  )rs   rt   r   )r7  r^   r_   r`   ru     s   )Zpandas.core.indexes.multir3  r   r   r<   r   r!  r  r   dtypesr   r   levelsr  mapr1   r   rg   r)  )r^   r   r3  r   Zfmt_columnsr;  r.  r_   )r7  r8  r^   r9  r`   r,    s,    

	z/DataFrameFormatter._get_formatted_column_labelsc                   s   dd j  D  |j}|j}d}t|trL|jjdj	|d}n|jj	|dg} fdd|D }j
jd| d
}jrdd  D }ndg|j }jr|| S |S d S )Nc                 S  s   i | ]\}}|t t|qS r_   )r   r   )rs   kvr_   r_   r`   r    s      z;DataFrameFormatter._get_formatted_index.<locals>.<dictcomp>	__index__F)r   rD   r   r0  )r   r0  c              
     s.   g | ]&}t tt|d  ddjdqS )rI   r\   r   )rE   r&  r   )r"  r+  r!  r   r   r   r   r^   r_   r`   ru     s     
 z;DataFrameFormatter._get_formatted_index.<locals>.<listcomp>r   rf   c                 S  s   g | ]}t |qS r_   rU   r   r_   r_   r`   ru     s     r\   )r   )r   itemsr   r   r/  r   r<   r   r   r  r   rD   splitr  _get_column_name_listZnlevelsr   )r^   r   r   r   fmtr   ZadjoinedZ
col_headerr_   rA  r`   r     s,    

	z'DataFrameFormatter._get_formatted_indexc                 C  sL   g }| j j}t|tr.|dd |jD  n||jd kr@dn|j |S )Nc                 s  s   | ]}|d krdn|V  qd S r[   r_   r   r_   r_   r`   r     s     z;DataFrameFormatter._get_column_name_list.<locals>.<genexpr>r\   )r   r   r   r<   extendr   ry   r   )r^   r   r   r_   r_   r`   rE    s    
z(DataFrameFormatter._get_column_name_list)NNTTrR   NNNNTNNNFr   FT)(r~   r   r   __doc__common_docstringreturn_docstringra   r   propertyr   r   r  r   r  r  r  r  r  r	  r   r   r   r   r   r   r   r  r  r  r  r  r   r  r  r   r*  r/  r,  r   rE  r_   r_   r_   r`   r   *  s~                    2/
/)(r   c                   @  s   e Zd ZdZddddZd%dd	d
d	d
d	d
d	d	d	d	dddZd&dd	dd
dd	d
d	dddZd'dd	dd	dddZd(dd	ddddd ddd	dd	d
d	dd!d	d"d#d$ZdS ))DataFrameRendereraJ  Class for creating dataframe output in multiple formats.

    Called in pandas.core.generic.NDFrame:
        - to_csv
        - to_latex

    Called in pandas.core.frame.DataFrame:
        - to_html
        - to_string

    Parameters
    ----------
    fmt : DataFrameFormatter
        Formatter with the formatting options.
    r   rF  c                 C  s
   || _ d S r   rM  )r^   rF  r_   r_   r`   ra     s    zDataFrameRenderer.__init__NF"FilePath | WriteBuffer[str] | Noner   rT   )rW   column_format	longtabler   multicolumnmulticolumn_formatmultirowcaptionr'  positionrc   c                 C  s>   ddl m} || j|||||||	|
d	}| }t|||dS )zU
        Render a DataFrame to a LaTeX tabular/longtable environment output.
        r   )LatexFormatter)rP  rO  rQ  rR  rS  rT  r'  rU  rW   r   )Zpandas.io.formats.latexrV  rF  r}   save_to_buffer)r^   rW   rO  rP  r   rQ  rR  rS  rT  r'  rU  rV  Zlatex_formatterstringr_   r_   r`   to_latex  s    zDataFrameRenderer.to_latexzstr | list | tuple | Noner   )rW   r   classesnotebookbordertable_idrender_linksrc   c                 C  sF   ddl m}m}	 |r|	n|}
|
| j||||d}| }t|||dS )uJ  
        Render a DataFrame to a html table.

        Parameters
        ----------
        buf : str, path object, file-like object, or None, default None
            String, path object (implementing ``os.PathLike[str]``), or file-like
            object implementing a string ``write()`` function. If None, the result is
            returned as a string.
        encoding : str, default “utf-8”
            Set character encoding.
        classes : str or list-like
            classes to include in the `class` attribute of the opening
            ``<table>`` tag, in addition to the default "dataframe".
        notebook : {True, False}, optional, default False
            Whether the generated HTML is for IPython Notebook.
        border : int
            A ``border=border`` attribute is included in the opening
            ``<table>`` tag. Default ``pd.options.display.html.border``.
        table_id : str, optional
            A css id is included in the opening `<table>` tag if specified.
        render_links : bool, default False
            Convert URLs to HTML links.
        r   )HTMLFormatterNotebookFormatter)r[  r]  r^  r_  rW  )Zpandas.io.formats.htmlr`  ra  rF  r}   rX  )r^   rW   r   r[  r\  r]  r^  r_  r`  ra  ZKlassZhtml_formatterrY  r_   r_   r`   to_html  s    "zDataFrameRenderer.to_html)rW   r   r   rc   c                 C  s0   ddl m} || j|d}| }t|||dS )u%  
        Render a DataFrame to a console-friendly tabular output.

        Parameters
        ----------
        buf : str, path object, file-like object, or None, default None
            String, path object (implementing ``os.PathLike[str]``), or file-like
            object implementing a string ``write()`` function. If None, the result is
            returned as a string.
        encoding: str, default “utf-8”
            Set character encoding.
        line_width : int, optional
            Width to wrap a line in characters.
        r   )StringFormatter)r   rW  )Zpandas.io.formats.stringrc  rF  r}   rX  )r^   rW   r   r   rc  Zstring_formatterrY  r_   r_   r`   r}   Q  s    zDataFrameRenderer.to_string,winfer"Tstrictz7FilePath | WriteBuffer[bytes] | WriteBuffer[str] | NonerU   zSequence[Hashable] | NonezIndexLabel | Noner    r%   )path_or_bufr   sepr   index_labelr   compressionr]   	quotecharline_terminator	chunksizedate_formatdoublequote
escapecharerrorsstorage_optionsrc   c                 C  s   ddl m} |dkr d}t }nd}|||
||||||||||	||||| jd}|  |r~t|tsjt| }|  |S dS )z;
        Render dataframe as comma-separated file.
        r   )CSVFormatterNTF)ri  rn  rj  r   rs  rl  r]   r  rk  r   ro  rm  rp  rq  rr  rt  r0  )	Zpandas.io.formats.csvsru  r   rF  saver   r   getvalueclose)r^   ri  r   rj  r   rk  r   rl  r]   rm  rn  ro  rp  rq  rr  rs  rt  ru  Zcreated_bufferZcsv_formattercontentr_   r_   r`   to_csvk  s>    zDataFrameRenderer.to_csv)
NNFNFNFNNN)NNNFNNF)NNN)NNrd  NNre  rf  Nrg  NNNTNrh  N)	r~   r   r   rH  ra   rZ  rb  r}   rz  r_   r_   r_   r`   rL    sT             $"       5                   rL  rU   rN  r   )rY  rW   r   rc   c              
   C  sL   t ||d6}||  |dkr4| W  5 Q R  S W 5 Q R  dS Q R X dS )zQ
    Perform serialization. Write to buf or return as string if buf is None.
    )r   N)
get_bufferwriterw  )rY  rW   r   fr_   r_   r`   rX    s
    
rX  rW  c              	   c  s   | dk	rt | } nt } |dkr&d}nt| ts8tdt| drJ| V  nBt| trtt|  t| d|dd}|V  W 5 Q R X ntddS )	z
    Context manager to open, yield and close buffer for filenames or Path-like
    objects, otherwise yield buf unchanged.
    Nzutf-8z1buf is not a file name and encoding is specified.r|  re  r\   )r   newlinez1buf is not a file name and it has no write method)	rC   r   r   rU   r  hasattrrB   open	TypeError)rW   r   r}  r_   r_   r`   r{    s    



r{  rR   rJ   r   Tr   r2  r   r   zstr | int | Noner   rk   )r{   r0  rl   rY   digitsr   rE   r   r   r]   rc   c
                 C  s   t | jrt}
n^t| jr t}
nNt| jr0t}
n>t| jr@t}
n.t	| jsTt
| jrZt}
nt| jrjt}
nt}
|dkr~td}|dkrtd}|dkrtd}|
| |||||||||	d
}| S )ad  
    Format an array for printing.

    Parameters
    ----------
    values
    formatter
    float_format
    na_rep
    digits
    space
    justify
    decimal
    leading_space : bool, optional, default True
        Whether the array should be formatted with a leading space.
        When an array as a column of a Series or DataFrame, we do want
        the leading space to pad between columns.

        When formatting an Index subclass
        (e.g. IntervalIndex._format_native_types), we don't want the
        leading space since it should be left-aligned.

    Returns
    -------
    List[str]
    Ndisplay.column_spacer   display.precision)	r  rY   rl   r0  r   rE   r   r   r]   )r)   r   Datetime64Formatterr*   Datetime64TZFormatterr3   Timedelta64Formatterr+   ExtensionArrayFormatterr-   r(   FloatArrayFormatterr/   IntArrayFormatterGenericArrayFormatterr   
get_result)r{   r0  rl   rY   r  r   rE   r   r   r]   Z	fmt_klassZfmt_objr_   r_   r`   rm     s@    '




rm   c                   @  sL   e Zd Zddd	d
dddddddddddZddddZddddZdS )r     NrR      rJ   r   Tr   r   r2  rU   r1  r   r   rT   r   )r{   r  r0  rY   r   rl   rE   r   r]   fixed_widthr   c                 C  sF   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
d S r   )r{   r  rY   r   r0  rl   rE   r   r]   r  r   )r^   r{   r  r0  rY   r   rl   rE   r   r]   r  r   r_   r_   r`   ra   (  s    zGenericArrayFormatter.__init__rk   rb   c                 C  s   |   }t|| jS r   )_format_stringsr+  rE   )r^   rz   r_   r_   r`   r  B  s    z GenericArrayFormatter.get_resultc                   sf  j d kr0td}|d kr6tdfdd}nj }jd k	rHj n"jd k	oZjtk}ttd|d  fdd}tjd	d
}t	|t
jstdt|t}|t
jt|ttdt|jd@ }j}|d kr| }g }t|D ]r\}	}
||	 s|r|d||
  q||	 r6|||
 q|dkrFd}nd}||j||
d q|S )Nr   r  c                   s   t | d ddS )Nz .dr}  )_trim_zeros_single_floatr:  )	precisionr_   r`   <lambda>K  s   z7GenericArrayFormatter._format_strings.<locals>.<lambda>r   )r   quote_stringsc              	     s   j d k	rvt| rvt| rvz<| d kr*W dS | tkr<ttW S | tksNt| rTW dS W n tt	fk
rn   Y nX j S t
| trt| S t | S d S )Nr   r   )rY   r2   r4   r   rU   r   npZisnatr  r  r   r9   r:  )r0  r^   r_   r`   _format[  s    


z6GenericArrayFormatter._format_strings.<locals>._formatTZextract_numpyz<ExtensionArray formatting should use ExtensionArrayFormatterr   r   r5  Fz{v}z {v}r?  )rl   r   r0  r]   r   r   rF   r:   r{   r   r  ndarrayr  r   Z	map_inferr,   r  r5   r"  rangerg   shaper   r   r)  ry   r   )r^   rl   r  r  valsinferredZis_float_typer   rz   rt   r?  Ztplr_   )r0  r  r^   r`   r  F  sN    

 

z%GenericArrayFormatter._format_strings)
r  NrR   r  NrJ   r   NTT)r~   r   r   ra   r  r  r_   r_   r_   r`   r  '  s             $r  c                      sL   e Zd Z fddZddddddd	Zd
dddZddddZ  ZS )r  c                   sD   t  j|| | jd k	r@| jd kr@d| _t| jr@| j| _d | _d S )NF)r   ra   rl   r0  r  callable)r^   argsr   r   r_   r`   ra     s    
zFloatArrayFormatter.__init__Nr   zfloat | int | Noner   )rl   	thresholdrc   c                   sl   dkrj r"fdd nfdd jdkrH fddn dkrXS fdd	}|S )
z;Returns a function to be applied on each value to format itNc                   s$    d k	st t| r | dS jS )Nvalue)r   r5   rY   r  )rl   r^   r_   r`   base_formatter  s
    z<FloatArrayFormatter._value_formatter.<locals>.base_formatterc                   s   t | rt| S  jS r   )r5   rU   rY   r  ro   r_   r`   r    s    r   c                   s    |  djdS )Nr   r   )replacer   r  )r  r^   r_   r`   decimal_formatter  s    z?FloatArrayFormatter._value_formatter.<locals>.decimal_formatterc                   s0   t | r&t| kr | S  dS njS d S )Ng        )r5   absrY   r  )r  r^   r  r_   r`   r0    s
    
z7FloatArrayFormatter._value_formatter.<locals>.formatter)rl   r   )r^   rl   r  r0  r_   )r  r  rl   r^   r  r`   _value_formatter  s    
	z$FloatArrayFormatter._value_formatter
np.ndarrayrb   c           
   	     sp  dddddd j dk	r. jj jS jr>tdnd fd	d
}jdkrjrjdkrrd}nd}t|jj	d}qj}nfdd}||}js|S t
|dkrtdd |D }|j	d k}nd}tjdd: tj}|dk }|dj	  k |dk@  }	W 5 Q R X |	s>|rl|rljdkrPd}nd}t|jj	d}||}|S )z
        Returns the float values converted into strings using
        the parameters given at initialisation, as a numpy array
        r   r   rU   )r{   r0  rY   c                   s<   t | }t fddt|  | D | j}|S )Nc                   s    g | ]\}}|s |nqS r_   r_   )rs   valmr0  rY   r_   r`   ru     s   zWFloatArrayFormatter.get_result_as_array.<locals>.format_with_na_rep.<locals>.<listcomp>)r4   r  arrayr  ravelZreshaper  )r{   r0  rY   mask	formattedr_   r  r`   format_with_na_rep  s    zCFloatArrayFormatter.get_result_as_array.<locals>.format_with_na_repNzdisplay.chop_thresholdc                   sx    | }jdkr"dj }nj}j}t|} |||}jrt|rZt|j}nt|j}t	j
|ddS |S )NrI   r5  objectr   )r  rE   rY   r{   r(   r  _trim_zeros_complexr   _trim_zeros_floatr  asarray)rl   r0  rY   r{   Z
is_complexr|   r  r^   r  r_   r`   format_values_with  s    
zCFloatArrayFormatter.get_result_as_array.<locals>.format_values_withTz{value: .{digits:d}f}z{value:.{digits:d}f})r  c                   s
    j |  S r   )rl   r  ro   r_   r`   r        z9FloatArrayFormatter.get_result_as_array.<locals>.<lambda>r   c                 s  s   | ]}t |V  qd S r   r   r   r_   r_   r`   r      s     z:FloatArrayFormatter.get_result_as_array.<locals>.<genexpr>   Fignoreinvalidg    .A
   z{value: .{digits:d}e}z{value:.{digits:d}e})r0  r{   rY   r  r   rl   r   r   r   r  rg   r-  r  errstater  r   )
r^   r  Zfmt_strrl   Zformatted_valuesmaxlenZtoo_longZabs_valsZhas_large_valuesZhas_small_valuesr_   r  r`   get_result_as_array  sD    




z'FloatArrayFormatter.get_result_as_arrayrk   c                 C  s   t |  S r   )r!  r  ro   r_   r_   r`   r  9  s    z#FloatArrayFormatter._format_strings)NN)r~   r   r   ra   r  r  r  r   r_   r_   r   r`   r    s     8cr  c                   @  s   e Zd ZddddZdS )r  rk   rb   c                   s>   | j dkrdd }ndd }| jp$|  fdd| jD }|S )NFc                 S  s   | dj | dS )Nr  r:  r   r:  r_   r_   r`   r  @  r  z3IntArrayFormatter._format_strings.<locals>.<lambda>c                 S  s   | dj | dS )Nz dr:  r  r:  r_   r_   r`   r  B  r  c                   s   g | ]} |qS r_   r_   r   r0  r_   r`   ru   D  s     z5IntArrayFormatter._format_strings.<locals>.<listcomp>)r   r0  r{   )r^   Zformatter_strrz   r_   r  r`   r  >  s    


z!IntArrayFormatter._format_stringsNr~   r   r   r  r_   r_   r_   r`   r  =  s   r  c                      s6   e Zd Zddddd fddZd	d
ddZ  ZS )r  r   Nz3np.ndarray | Series | DatetimeIndex | DatetimeArrayrU   r   )r{   nat_reprp  c                   s    t  j|f| || _|| _d S r   )r   ra   r  rp  )r^   r{   r  rp  r   r   r_   r`   ra   I  s    zDatetime64Formatter.__init__rk   rb   c                   sZ    j }t|tst|} jdk	r>t jr> fdd|D S |jj j jd}|	 S )z&we by definition have DO NOT have a TZNc                   s   g | ]}  |qS r_   r  r   ro   r_   r`   ru   \  s     z7Datetime64Formatter._format_strings.<locals>.<listcomp>)rY   rp  )
r{   r   r?   r0  r  _dataZ_format_native_typesr  rp  tolist)r^   r{   rz   r_   ro   r`   r  T  s    
 z#Datetime64Formatter._format_strings)r   Nr~   r   r   ra   r  r   r_   r_   r   r`   r  H  s     r  c                   @  s   e Zd ZddddZdS )r  rk   rb   c                 C  sv   t | jdd}| j}|d kr(|jdd}t|tr<| }n
t|}t	||| j
| j| j| j| j| j| j| jd
}|S )NTr  )Zboxed)rl   rY   r  r   rE   r   r   r]   )r:   r{   r0  
_formatterr   r6   rn   r  r  rm   rl   rY   r  r   rE   r   r   r]   )r^   r{   r0  r  rz   r_   r_   r`   r  e  s(    


z'ExtensionArrayFormatter._format_stringsNr  r_   r_   r_   r`   r  d  s   r  z@np.ndarray | list[int | float] | list[float] | list[str | float])percentilesrc   c                 C  sR  t | } t jdd2 t| r<t | dkr<t | dksDtdW 5 Q R X d|  } t | t| }t |r| tt	}dd |D S t 
| }|d dkr|d nd	}|d
 dk rd|d
  nd	}t t t t j|||dt }td|}t j| td}| | tt	||< | |  |t	|| < dd |D S )a  
    Outputs rounded and formatted percentiles.

    Parameters
    ----------
    percentiles : list-like, containing floats from interval [0,1]

    Returns
    -------
    formatted : list of strings

    Notes
    -----
    Rounding precision is chosen so that: (1) if any two elements of
    ``percentiles`` differ, they remain different after rounding
    (2) no entry is *rounded* to 0% or 100%.
    Any non-integer is always rounded to at least 1 decimal place.

    Examples
    --------
    Keeps all entries different after rounding:

    >>> format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999])
    ['1.999%', '2.001%', '50%', '66.667%', '99.99%']

    No element is rounded to 0% or 100% (unless already equal to it).
    Duplicates are allowed:

    >>> format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999])
    ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%']
    r  r  r   r   z/percentiles should all be in the interval [0,1]d   c                 S  s   g | ]}|d  qS %r_   rr   r_   r_   r`   ru     s     z&format_percentiles.<locals>.<listcomp>N)to_beginto_endr  c                 S  s   g | ]}|d  qS r  r_   rr   r_   r_   r`   ru     s     )r  r  r  r1   r  r  iscloseastyper   rU   uniquefloorlog10r   Zediff1dr-  Z
empty_liker  round)r  Zint_idxoutZunique_pctsr  r  precr_   r_   r`   format_percentiles  s6    "



r  z2np.ndarray | DatetimeArray | Index | DatetimeIndexrT   r{   rc   c                 C  sf   t | ts|  } t| } | jd k	r(dS | j}|tk}d}t||t	| dk
 dk}|rbdS dS )NF     "R: r   T)r   r;   r  r?   tzZasi8r   r  logical_andr   r   )r{   
values_intconsider_valuesone_day_nanos	even_daysr_   r_   r`   is_dates_only  s    

r  r   zNaTType | Timestamp)r   r  rc   c                 C  s   | t kr|S t| S r   )r   rU   )r   r  r_   r_   r`   _format_datetime64  s    r  )r   r  rp  rc   c                 C  s$   | t kr|S |r| |S | jS d S r   )r   strftimeZ
_date_repr)r   r  rp  r_   r_   r`   _format_datetime64_dateonly  s
    
r  r   )r  r  rp  rc   c                   s"   | r fddS fddS d S )Nc                   s   t |  dS )N)r  rp  )r  r:  rp  r  r_   r`   r    s     z'get_format_datetime64.<locals>.<lambda>c                   s   t |  dS )Nr  )r  r:  r  r_   r`   r    r  r_   )r  r  rp  r_   r  r`   get_format_datetime64  s    r  z*np.ndarray | DatetimeArray | DatetimeIndex)r{   rp  rc   c                 C  s6   t | tjr| jdkr|  } t| }|r2|p0dS |S )z6given values and a date_format, return a string formatr   z%Y-%m-%d)r   r  r  ndimr  r  )r{   rp  idor_   r_   r`   !get_format_datetime64_from_values   s    r  c                   @  s   e Zd ZddddZdS )r  rk   rb   c                   s>   | j t}t|}| jp&t|| jd  fdd|D }|S )zwe by definition have a TZ)rp  c                   s   g | ]} |qS r_   r_   r   r  r_   r`   ru     s     z9Datetime64TZFormatter._format_strings.<locals>.<listcomp>)r{   r  r  r  r0  r  rp  )r^   r{   r  rz   r_   r  r`   r    s     z%Datetime64TZFormatter._format_stringsNr  r_   r_   r_   r`   r    s   r  c                      s6   e Zd Zddddd fddZd	d
ddZ  ZS )r  r   Fznp.ndarray | TimedeltaIndexrU   rT   )r{   r  boxc                   s    t  j|f| || _|| _d S r   )r   ra   r  r  )r^   r{   r  r  r   r   r_   r`   ra     s    zTimedelta64Formatter.__init__rk   rb   c                   s.   | j pt| j| j| jd  fdd| jD S )N)r  r  c                   s   g | ]} |qS r_   r_   r   r  r_   r`   ru   ,  s     z8Timedelta64Formatter._format_strings.<locals>.<listcomp>)r0  get_format_timedelta64r{   r  r  ro   r_   r  r`   r  (  s      z$Timedelta64Formatter._format_strings)r   Fr  r_   r_   r   r`   r    s     r  Fz,np.ndarray | TimedeltaIndex | TimedeltaArray)r{   r  r  rc   c           
        s^   |  tj}|tk}d}|| dk}t||}| dk}|rFdnd fdd}	|	S )z
    Return a formatter function for a range of timedeltas.
    These will all have the same format argument

    If box, then show the return in quotes
    r  r   Nlongc                   sN   | d kst | rt| rS t| ts.t| } | jd} rJd| d}|S )Nr  ')r2   r4   r   r   Z
_repr_base)r   r|   r  r   r  r_   r`   r  N  s    
z*get_format_timedelta64.<locals>._formatter)viewr  Zint64r   r  r   )
r{   r  r  r  r  r  Znot_midnightZbothr  r  r_   r  r`   r  /  s    r  zTextAdjustment | None)r%  rE   r&  r   rc   c                   s   t | dks|dkr| S |d kr(t  n| t fdd| D |d k	rTt|tdd k	rpkrpddd fdd	fd
d| D }  j| |d}|S )Nr   r  c                 3  s   | ]}  |V  qd S r   r   r   )
adjustmentr_   r`   r   k  s     z$_make_fixed_width.<locals>.<genexpr>r   rU   )r   rc   c                   s6   d k	r2dk  | k@ r2| d d  d } | S )Nr   r   r   r:  )r  conf_maxr   r_   r`   justt  s    z_make_fixed_width.<locals>.justc                   s   g | ]} |qS r_   r_   r   )r  r_   r`   ru   z  s     z%_make_fixed_width.<locals>.<listcomp>r   )rg   r   r-  r   rE   )r%  rE   r&  r   r|   r_   )r  r  r  r   r`   r+  \  s    
r+  r  )str_complexesr   rc   c                   sD    fdd| D }dd |D }t |fddt||D }|S )z
    Separates the real and imaginary parts from the complex number, and
    executes the _trim_zeros_float method on each of those.
    c              	     s$   g | ]}d  ttd| qS )r\   z([j+-]))rx   r  rerD  r   )r   r_   r`   ru     s   z'_trim_zeros_complex.<locals>.<listcomp>c                 S  s   g | ]}t |qS r_   r   )rs   sr_   r_   r`   ru     s     c                   s   g | ]\}}|d |d d d    | d d  ||d d d  |d d    ||d d  d   | d d  |d  qS )Nr   r   0r  r_   )rs   r  r>  )
max_lengthr_   r`   ru     s   ")r-  r  )r  r   trimmedlengthspaddedr_   )r   r  r`   r    s    

	r  )	str_floatrc   c                 C  s    |  d} | dr| d7 } | S )zX
    Trims trailing zeros after a decimal point,
    leaving just one if necessary.
    r  r   )rstripendswith)r  r_   r_   r`   r    s    

r  np.ndarray | list[str])
str_floatsr   rc   c                   sj   | }t d  dfdddddfdd	}||rRfd
d|D }q6 fdd|D }|S )z
    Trims the maximum number of trailing zeros equally from
    all numbers containing decimals, leaving just one if
    necessary.
    z^\s*[\+-]?[0-9]+\z[0-9]*$c                   s   t  | d k	S r   )r  matchr:  )number_regexr_   r`   is_number_with_decimal  s    z1_trim_zeros_float.<locals>.is_number_with_decimalr   rT   r  c                   s0    fdd| D }t |dko.tdd |D S )z
        Determine if an array of strings should be trimmed.

        Returns True if all numbers containing decimals (defined by the
        above regular expression) within the array end in a zero, otherwise
        returns False.
        c                   s   g | ]} |r|qS r_   r_   r   r  r_   r`   ru     s      z:_trim_zeros_float.<locals>.should_trim.<locals>.<listcomp>r   c                 s  s   | ]}| d V  qdS )r  Nr  r   r_   r_   r`   r     s     z9_trim_zeros_float.<locals>.should_trim.<locals>.<genexpr>)rg   r  )r{   numbersr  r_   r`   should_trim  s    z&_trim_zeros_float.<locals>.should_trimc                   s$   g | ]} |r|d d n|qS )Nr  r_   r   r  r_   r`   ru     s     z%_trim_zeros_float.<locals>.<listcomp>c                   s*   g | ]"}|r"|  r"|d  n|qS )r  r  r   )r   r  r_   r`   ru     s   )r  compile)r  r   r  r  r|   r_   )r   r  r  r`   r    s    r  r;   )r   rc   c                 C  s$   t | trtj| j S | jd k	S d S r   )r   r<   comZany_not_noner   r   )r   r_   r_   r`   r    s    
r  c                   @  sZ   e Zd ZdZdddddddd	d
dddddddddZd dddddZdddddZdS )!EngFormatterzl
    Formats float values according to engineering format.

    Based on matplotlib.ticker.EngFormatter
    r6  zar}  pnur  r\   r>  MGTPEZY)iiiiiiir   r   r  	   r              NFr   rT   accuracyuse_eng_prefixc                 C  s   || _ || _d S r   r  )r^   r  r   r_   r_   r`   ra     s    zEngFormatter.__init__zint | floatrU   )numrc   c           
      C  s   t t|}t j|rdS t j|r.dS d}|dk rDd}| }|dkrnt tt| d d }n
t d}|	t
| j }|
t	| j }t|}| jr| j| }n$|dk rd| d}nd	|d}|| d
|  }| jdkrd}nd| jdd}|j||d}	|	S )a  
        Formats a number in engineering notation, appending a letter
        representing the power of 1000 of the original number. Some examples:
        >>> format_eng = EngFormatter(accuracy=0, use_eng_prefix=True)
        >>> format_eng(0)
        ' 0'
        >>> format_eng = EngFormatter(accuracy=1, use_eng_prefix=True)
        >>> format_eng(1_000_000)
        ' 1.0M'
        >>> format_eng = EngFormatter(accuracy=2, use_eng_prefix=False)
        >>> format_eng("-1e-6")
        '-1.00E-06'

        @param num: the value to represent
        @type num: either a numeric value or a string that can be converted to
                   a numeric value (as per decimal.Decimal constructor)

        @return: engineering formatted string
        rR   infr   r   r  r   zE-02dzE+r  Nz{mant: g}{prefix}z{mant: .r  z
f}{prefix})mantprefix)r   DecimalrU   is_nanis_infiniter   mathr  r  r   r-  ENG_PREFIXESr  r   r  r   )
r^   r!  ZdnumsignZpow10Z	int_pow10r%  r$  
format_strr  r_   r_   r`   __call__  s4    "

zEngFormatter.__call__)NF)r~   r   r   rH  r*  ra   r-  r_   r_   r_   r`   r    s*   r  r   r   r   )r  r   rc   c                 C  s(   t dt| | t dtd| d  dS )z
    Alter default behavior on how float is formatted in DataFrame.
    Format float in engineering format. By accuracy, we mean the number of
    decimal digits after the floating point.

    See also EngFormatter.
    r   r  r  r  N)r   r  r-  r  r_   r_   r`   set_eng_float_format.  s    r.  r\   zbool | object | strzlist[dict[int, int]])r<  sentinelrc   c           	      C  s   t | dkrg S dgt | d  }g }| D ]b}d}i }t|D ]2\}}|| rX||krXq>d||< || ||< |}q>t || ||< || q*|S )a  
    For each index in each level the function returns lengths of indexes.

    Parameters
    ----------
    levels : list of lists
        List of values on for level.
    sentinel : string, optional
        Value which states that no new index starts on there.

    Returns
    -------
    Returns list of maps. For each level returns map of indexes (key is index
    in row and value is length of index).
    r   TF)rg   r)  ry   )	r<  r/  controlr|   r4  
last_indexr  rt   keyr_   r_   r`   get_level_lengths:  s     r3  zWriteBuffer[str])rW   linesrc   c                 C  s4   t dd |D r dd |D }| d| dS )z
    Appends lines to a buffer.

    Parameters
    ----------
    buf
        The buffer to write to
    lines
        The lines to append.
    c                 s  s   | ]}t |tV  qd S r   )r   rU   r   r_   r_   r`   r   p  s     z#buffer_put_lines.<locals>.<genexpr>c                 S  s   g | ]}t |qS r_   rB  r   r_   r_   r`   ru   q  s     z$buffer_put_lines.<locals>.<listcomp>rf   N)r   r|  rx   )rW   r4  r_   r_   r`   buffer_put_linese  s    r5  )NN)N)NrR   NNrJ   r   TN)r   )r   N)r   N)r   F)rJ   NN)r   )r   )r   F)r\   )rH  
__future__r   
contextlibr   csvr   r   r   	functoolsr   ior   r)  r  shutilr   typingr	   r
   r   r   r   r   r   r   r   r   unicodedatar   numpyr  Zpandas._config.configr   r   Zpandas._libsr   Zpandas._libs.missingr   Zpandas._libs.tslibsr   r   r   r   Zpandas._libs.tslibs.nattyper   Zpandas._typingr   r   r   r    r!   r"   r#   r$   r%   r&   Zpandas.core.dtypes.commonr'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   Zpandas.core.dtypes.missingr4   r5   Zpandas.core.arraysr6   r7   r8   Zpandas.core.baser9   Zpandas.core.commoncorecommonr
  Zpandas.core.constructionr:   Zpandas.core.indexes.apir;   r<   r=   r>   Zpandas.core.indexes.datetimesr?   Zpandas.core.indexes.timedeltasr@   Zpandas.core.reshape.concatrA   Zpandas.io.commonrB   rC   Zpandas.io.formats.printingrD   rE   rF   ZpandasrG   rH   rI  Z_VALID_JUSTIFY_PARAMETERSrJ  rQ   r   r   r   r   r   r   r   rL  rX  r{  rm   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r+  r  r  r  r  r  r.  r3  r5  r_   r_   r_   r`   <module>   s   00<;	@ !'!&   C @  $        $Oj -E	       /   # $_ +