a
    d)                    @  s  U d Z ddlmZ ddlmZmZmZmZmZ ddl	m
Z
 ddlmZmZ ddlm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 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.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z= ddl>m?Z?m@Z@ ddlAmBZBmCZCmDZD ddlEmFZF ddlGmHZH dd	lImJ  mKZL ddlMmNZN ddlOmPZPmQZQmRZRmSZS ddlTmUZU ddlVmWZW ddlXmYZY ddlZm[Z[m\Z\ ddl]m^Z^ erBddl_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZj dd lkmlZlmmZm d!Znd"eod#< d$Zpd%Zqd"eod&< G d'd( d(ZrG d)d* d*ZsG d+d, d,ZtG d-d. d.etZud,d/d0d1Zvd2d/d3d4Zwd2d/d5d6ZxG d7d8 d8ZyG d9d: d:Zzdd;d<d=d=d>d?d@Z{e
dd<d=dAdBdCdDZ|ddIdJdKd;dLdMd;d;dNdLdJdOdPdQdRZ}G dSdT dTZ~G dUdV dVe~ZG dWdX dXe~ZG dYdZ dZe~ZG d[d\ d\e~Zd]dOd^d_d`ZdadbdcdddeZddgd;d;dhdidjZddgd;d=d;dkdldmZddbd;d=dndodpdqZdrd=d=dsdtduZG dvdw dweZG dxdy dye~Zdd{d|dbdnd}d~dZddOd;dLddOdddZddd;dOdddZd;d;dddZddd;dOdddZddbdddZG dd dZdddbddddZddIdddddZddOdd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)	GeneratorHashableIterableMappingSequence)contextmanager)
QUOTE_NONEQUOTE_NONNUMERIC)Decimal)partial)StringION)get_terminal_size)IOTYPE_CHECKINGAnyCallableFinalcast)east_asian_width)
get_option
set_option)lib)NA)NaT	Timedelta	Timestampget_unit_from_dtypeiNaTperiods_per_day)NaTType)is_complex_dtypeis_float
is_integeris_list_likeis_numeric_dtype	is_scalar)CategoricalDtypeDatetimeTZDtypeExtensionDtype)isnanotna)CategoricalDatetimeArrayTimedeltaArray)StringDtype)PandasObject)extract_array)Index
MultiIndexPeriodIndexensure_index)DatetimeIndex)TimedeltaIndex)concat)check_parent_directorystringify_path)printing)	ArrayLikeAxesColspaceArgTypeColspaceTypeCompressionOptionsFilePathFloatFormatTypeFormattersType
IndexLabelStorageOptionsWriteBuffer)	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 : array-like, 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.
    r   common_docstring)leftrightcenterjustifyzjustify-allstartendZinheritzmatch-parentinitialZunsetz
        Returns
        -------
        str or None
            If buf is None, returns the result as a string. Otherwise returns
            None.
    return_docstringc                   @  sP   e Zd Z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S )CategoricalFormatterNTNaNr,   IO[str] | NoneboolstrNone)categoricalbuflengthna_repfooterreturnc                 C  s8   || _ |d ur|ntd| _|| _|| _|| _t| _d S N )rX   r   rY   r[   rZ   r\   r
   quoting)selfrX   rY   rZ   r[   r\    rb   a/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pandas/io/formats/format.py__init__   s    zCategoricalFormatter.__init__r]   c                 C  sP   d}| j r*|r|d7 }|dt| j 7 }| j }|r@|d7 }||7 }t|S )Nr_   , Length: 
)rZ   lenrX   _repr_categories_inforV   )ra   r\   
level_inforb   rb   rc   _get_footer   s    
z CategoricalFormatter._get_footer	list[str]c                 C  s   t | j d d | j| jdS )N)float_formatr[   r`   )format_arrayrX   _internal_get_valuesr[   r`   ra   rb   rb   rc   _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 rb   )strip.0irb   rb   rc   
<listcomp>       z2CategoricalFormatter.to_string.<locals>.<listcomp>rf   []rh   )rX   ri   r\   rl   rr   joinappendrV   )ra   rX   
fmt_valuesvaluesresultr\   rb   rb   rc   	to_string   s    

zCategoricalFormatter.to_string)NTrS   T)__name__
__module____qualname__rd   rl   rr   r   rb   rb   rb   rc   rR      s       	rR   c                   @  sx   e Zd Zd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 )SeriesFormatterNTrS   FrH   rT   
bool | strrU   rV   
str | None
int | NonerW   )seriesrY   rZ   headerindexr[   namern   dtypemax_rowsmin_rowsr]   c                 C  st   || _ |d ur|nt | _|| _|| _|| _|| _|| _|
| _|| _	|d u rTt
d}|| _|	| _t | _|   d S )Ndisplay.float_format)r   r   rY   r   r[   r   rZ   r   r   r   r   rn   r   get_adjustmentadj_chk_truncate)ra   r   rY   rZ   r   r   r[   r   rn   r   r   r   rb   rb   rc   rd   	  s    zSeriesFormatter.__init__re   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   ri   r   r   intminilocr8   
tr_row_num	tr_seriesis_truncated_vertically)ra   r   r   r   r   row_numrb   rb   rc   r   )  s$    

"zSeriesFormatter._chk_truncatec                 C  sH  | j j}d}t| j jdd d urLt| j jtttfs8J |d| j jj 7 }| jdur|d ur|rj|d7 }t	j
|dd}|d| 7 }| jd	u s| jd
kr| jr|r|d7 }|dt| j  7 }| jdur| jd urt| jjdd }|r|r|d7 }|dt	
| 7 }t| jjtr@| jj }|r8|d7 }||7 }t|S )Nr_   freqzFreq: Frf   	rh   )escape_charszName: Ttruncaterg   r   zdtype: rh   )r   r   getattrr   
isinstancer6   r4   r7   Zfreqstrr;   pprint_thingrZ   r   ri   r   r   r'   _valuesrj   rV   )ra   r   r\   Zseries_nameZ
dtype_namerk   rb   rb   rc   rl   D  s@    
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 u}|jdd}||fS )Nc                 s  s   | ]
}|V  qd S Nrb   ru   r   rb   rb   rc   	<genexpr>q  rx   z7SeriesFormatter._get_formatted_index.<locals>.<genexpr>T)names)r   )r   r   r   r3   anyr   formatr   )ra   r   have_header	fmt_indexrb   rb   rc   _get_formatted_indexm  s    

z$SeriesFormatter._get_formatted_indexrm   c                 C  s   t | jjd | j| j| jdS )N)rn   r[   leading_space)ro   r   r   rn   r[   r   rq   rb   rb   rc   rr   x  s    z%SeriesFormatter._get_formatted_valuesc                 C  s2  | 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g|dd  |gR  }
n| jd|}
| jr|r|d d |
 }
|r$|
d| 7 }
td
|
S )Nr   z([], )r      ...z..rL   moder_   rh   )r   rl   ri   typer   r   r   rr   r   r   r   r   r   rM   insertr   adjoinr   rV   r{   )ra   r   r\   r   r   r}   Zn_header_rowsr   widthZdot_strr   rb   rb   rc   r     s2    
"zSeriesFormatter.to_string)
NTTTrS   FNTNN)	r   r   r   rd   r   rl   r   rr   r   rb   rb   rb   rc   r     s              & )	r   c                   @  sP   e Zd Zdd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 )TextAdjustmentrW   re   c                 C  s   t d| _d S )Nzdisplay.encoding)r   encodingrq   rb   rb   rc   rd     s    zTextAdjustment.__init__rV   r   textr]   c                 C  s   t |S r   ri   ra   r   rb   rb   rc   ri     s    zTextAdjustment.lenrK   r   rm   textsmax_lenr   r]   c                 C  s   t j|||dS )Nr   )r;   rM   ra   r   r   r   rb   rb   rc   rM     s    zTextAdjustment.justify)spacer]   c                 O  s"   t j|g|R | j| jd|S )N)ZstrlenZjustfunc)r;   r   ri   rM   )ra   r   listskwargsrb   rb   rc   r     s    zTextAdjustment.adjoinN)rK   )r   r   r   rd   ri   rM   r   rb   rb   rb   rc   r     s   r   c                      sH   e Zd Zdd fddZddddd	ZddddddddZ  ZS )EastAsianTextAdjustmentrW   re   c                   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)superrd   r   ambiguous_width_EAW_MAPrq   	__class__rb   rc   rd     s
    
z EastAsianTextAdjustment.__init__rV   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   )ru   crq   rb   rc   r     s   z.EastAsianTextAdjustment.len.<locals>.<genexpr>)r   rV   ri   sumr   rb   rq   rc   ri     s
    
zEastAsianTextAdjustment.lenrK   zIterable[str]rm   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   ra   rb   rc   _get_pad  s    z1EastAsianTextAdjustment.justify.<locals>._get_padrJ   c                   s   g | ]}|  |qS rb   )ljustru   xr   rb   rc   rw     rx   z3EastAsianTextAdjustment.justify.<locals>.<listcomp>rL   c                   s   g | ]}|  |qS rb   )rL   r   r   rb   rc   rw     rx   c                   s   g | ]}|  |qS rb   )rjustr   r   rb   rc   rw     rx   rb   r   rb   )r   r   ra   rc   rM     s    zEastAsianTextAdjustment.justify)rK   )r   r   r   rd   ri   rM   __classcell__rb   rb   r   rc   r     s    r   re   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_widthrb   rb   rc   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)pandas.io.formatsr   r   Zget_console_size)r   r   _rb   rb   rc   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   rZ   )r   r   )r   heightr   r   rb   rb   rc   get_series_repr_params  s    


r   c                   @  sX  e Zd ZdZerendZeee 7 Zdjdd	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/d0Zddd1d2d3Zdd4d5d6d7Zddd8d9d:Zd	d;d<d=d>Zd
d?d@dAdBZdddCdDZdddEdFZdddGdHdIZdddJdKZdddLdMZdddNdOZd.ddPdQZdddRdSZdddTdUZ dd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&dgddhdiZ'dS )kDataFrameFormatterz;Class for processing dataframe formatting options and data.r_   NTrS   F.rG   zAxes | NonezColspaceArgType | Nonezbool | list[str]rU   rV   zFormattersType | Noner   FloatFormatType | Nonebool | Noner   r   rW   )framecolumns	col_spacer   r   r[   
formattersrM   rn   sparsifyindex_namesr   r   r   r   decimal	bold_rowsescaper]   c                 C  s   || _ | || _| || _|| _|| _|| _| || _	| 
|| _|	| _| |
| _|| _|| _|| _|| _|| _|| _|| _|| _|  | _|  | _| j | _|   t | _d S r   )r   _initialize_columnsr   _initialize_colspacer   r   r   r[   _initialize_formattersr   _initialize_justifyrM   rn   _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   )ra   r   r   r   r   r   r[   r   rM   rn   r   r   r   r   r   r   r   r   r   rb   rb   rc   rd   4  s.    

zDataFrameFormatter.__init__zlist[list[str]]re   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   )ra   strcolsZ	str_indexrb   rb   rc   get_strcolsc  s
    zDataFrameFormatter.get_strcolsc                 C  s   | j du p| j dko| jS )NTr   )r   is_truncatedrq   rb   rb   rc   should_show_dimensionso  s    
z)DataFrameFormatter.should_show_dimensionsc                 C  s   t | jp| jS r   )rU   is_truncated_horizontallyr   rq   rb   rb   rc   r  u  s    zDataFrameFormatter.is_truncatedc                 C  s   t | jot| j| jkS r   )rU   r   ri   r   rq   rb   rb   rc   r  y  s    z,DataFrameFormatter.is_truncated_horizontallyc                 C  s   t | jot| j| jkS r   )rU   r   ri   r   rq   rb   rb   rc   r   }  s    z*DataFrameFormatter.is_truncated_verticallyc                 C  s    dt | j dt | jj dS )Nz

[z rows x z	 columns])ri   r   r   rq   rb   rb   rc   dimensions_info  s    z"DataFrameFormatter.dimensions_infoc                 C  s   t | jjS r   )
_has_namesr   r   rq   rb   rb   rc   has_index_names  s    z"DataFrameFormatter.has_index_namesc                 C  s   t | jjS r   )r  r   r   rq   rb   rb   rc   has_column_names  s    z#DataFrameFormatter.has_column_namesc                 C  s   t | j| j| jfS r   )allr  r   r   rq   rb   rb   rc   show_row_idx_names  s    z%DataFrameFormatter.show_row_idx_namesc                 C  s   t | j| j| jfS r   )r
  r	  r   r   rq   rb   rb   rc   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   ri   r   rq   rb   rb   rc   max_rows_displayed  s    z%DataFrameFormatter.max_rows_displayed)r   r]   c                 C  s   |d u rt dS |S )Nzdisplay.multi_sparser   )ra   r   rb   rb   rc   r     s    z'DataFrameFormatter._initialize_sparsifyrC   )r   r]   c                 C  sT   |d u 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   )ri   r   r   r   dict
ValueError)ra   r   rb   rb   rc   r     s    
z)DataFrameFormatter._initialize_formatters)rM   r]   c                 C  s   |d u rt dS |S d S )Nzdisplay.colheader_justifyr  )ra   rM   rb   rb   rc   r     s    z&DataFrameFormatter._initialize_justifyr2   )r   r]   c                 C  s,   |d ur t |}| j| | _|S | jjS d S r   )r5   r   r   )ra   r   colsrb   rb   rc   r     s
    z&DataFrameFormatter._initialize_columnsr?   )r   r]   c                   s    d u ri }nt  ttfrBd i}| fdd| jjD  nt  tr  D ]&}|| jjv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 rb   rb   )ru   columnr   rb   rc   
<dictcomp>  rx   z;DataFrameFormatter._initialize_colspace.<locals>.<dictcomp>z,Col_space is defined for an unknown column: zCol_space length(r  r   )r   r   rV   updater   r   r   keysr  ri   r  zip)ra   r   r   r  rb   r  rc   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)ra   r   r   rb   rb   rc   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_auxiliary_rows_is_screen_short_adjust_max_rows)ra   r   r   r   rb   rb   rc   r     s    


z(DataFrameFormatter._calc_max_rows_fitted)r   r]   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
        )ri   r   r   r   )ra   r   rb   rb   rc   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   )rU   r   r   rq   rb   rb   rc   r    s    z"DataFrameFormatter._is_in_terminalc                 C  s   t | jdkot| jj|kS Nr   )rU   r   ri   r   r   )ra   	max_widthrb   rb   rc   r    s    z$DataFrameFormatter._is_screen_narrowc                 C  s   t | jdkot| j|kS r  )rU   r   ri   r   )ra   Z
max_heightrb   rb   rc   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   ri   r  
splitlinesr   )ra   Zdot_rowZ
prompt_rowZnum_rowsrb   rb   rc   r    s    z0DataFrameFormatter._get_number_of_auxiliary_rowsc                 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_verticallyrq   rb   rb   rc   r     s    zDataFrameFormatter.truncatec                 C  s   | j dusJ | 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rg | 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   r8   r   r   listtupler   r   r   Z
tr_col_num)ra   Zcol_numrJ   rK   rb   rb   rc   r!    s    
z)DataFrameFormatter._truncate_horizontallyc                 C  s   | j dusJ | 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   r8   r   r   r   r   )ra   r   headtailrb   rb   rc   r"  9  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g fd	d
|D R  } |}t| j| j
d}tg  fdd
|D |R  }	 j
j||	 jd}|||  q|S )Nr   )stringsrM   minimumr   zWriting z cols but got z aliasesc                 S  s   g | ]
}|gqS rb   rb   )ru   labelrb   rb   rc   rw   b  rx   zADataFrameFormatter._get_strcols_without_index.<locals>.<listcomp>r_   c                 3  s   | ]} j |V  qd S r   r   ri   r   rq   rb   rc   r   m  rx   z@DataFrameFormatter._get_strcols_without_index.<locals>.<genexpr>)r)  r   c                 3  s   | ]} j |V  qd S r   r+  r   rq   rb   rc   r   t  rx   r   )r$   r   	enumerater   
format_col_make_fixed_widthrM   r   r   r   r   r|   r   r$  rV   ri   r   r  _get_formatted_column_labelsr  max)
ra   r  rv   r   r}   str_columnsr   ZcheaderZheader_colwidthr   rb   rq   rc   r   K  sP    


 z-DataFrameFormatter._get_strcols_without_indexrm   )rv   r]   c              	   C  sL   | j }| |}t|jd d |f j|| j| j| j|j	| | j
| jdS )N)rn   r[   r   r   r   )r   _get_formatterro   r   r   rn   r[   r   r   r   r   r   )ra   rv   r   	formatterrb   rb   rc   r-  z  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vrN| j| }| j|d S d S r   )	r   r   r$  r%  r#   r   r   r   r   )ra   rv   rb   rb   rc   r2    s    


z!DataFrameFormatter._get_formatter)r   r]   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   r   c                 s  s   | ]}|j V  qd S r   )Zis_floating)ru   levelrb   rb   rc   r     rx   zBDataFrameFormatter._get_formatted_column_labels.<locals>.<genexpr>c                   s"   |j vr |  rsd| S |S )N )r   )r   y)need_leadsprestrict_formattingra   rb   rc   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 rb   rb   )ru   r9  )r<  r   rb   rc   rw     rx   zMDataFrameFormatter._get_formatted_column_labels.<locals>.<genexpr>.<listcomp>Nrb   )ru   )r<  r   rc   r     rx   c                 S  s   g | ]}t |qS rb   )r$  r   rb   rb   rc   rw     rx   zCDataFrameFormatter._get_formatted_column_labels.<locals>.<listcomp>c                   s0   g | ](\}} |s& | r&d | n|gqS )r8  )r2  )ru   rv   r   )r:  ra   rb   rc   rw     s   )Zpandas.core.indexes.multir6  r   r   r3   r   r$  r  r   dtypesr   r   levelsr  mapr%   r   ri   r,  )ra   r   r6  r   Zfmt_columnsr>  r1  rb   )r:  r;  ra   r<  rc   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	g|R  d
}jrdd  D }ndg|j }jr|| S |S d S )Nc                 S  s   i | ]\}}|t t|qS rb   )r   r   )ru   kvrb   rb   rc   r    rx   z;DataFrameFormatter._get_formatted_index.<locals>.<dictcomp>	__index__F)r   r   r   r3  )r   r3  c              
     s.   g | ]&}t tt|d  ddjdqS )rJ   r_   r   )rM   r)  r   )r%  r.  r$  r   r   r   r   ra   rb   rc   rw     s   z;DataFrameFormatter._get_formatted_index.<locals>.<listcomp>r   rh   c                 S  s   g | ]}t |qS rb   rV   r   rb   rb   rc   rw     rx   r_   )r   itemsr   r   r2  r   r3   r   r   r  r   r   splitr  _get_column_name_listZnlevelsr   )ra   r   r   r   fmtr   ZadjoinedZ
col_headerrb   rD  rc   r     s,    

	z'DataFrameFormatter._get_formatted_indexzlist[Hashable]c                 C  sL   g }| j j}t|tr.|dd |jD  n||jd u r@dn|j |S )Nc                 s  s   | ]}|d u rdn|V  qd S r^   rb   r   rb   rb   rc   r     rx   z;DataFrameFormatter._get_column_name_list.<locals>.<genexpr>r_   )r   r   r   r3   extendr   r|   r   )ra   r   r   rb   rb   rc   rH    s    
z(DataFrameFormatter._get_column_name_list)NNTTrS   NNNNTNNNFr   FT)(r   r   r   __doc__rI   rQ   rd   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-  r2  r/  r   rH  rb   rb   rb   rc   r   .  s~                    4/
/)(r   c                   @  s   e Zd ZdZ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   rW   )rI  r]   c                 C  s
   || _ d S r   )rI  )ra   rI  rb   rb   rc   rd     s    zDataFrameRenderer.__init__NF"FilePath | WriteBuffer[str] | Noner   zstr | list | tuple | NonerU   zint | bool | None)rY   r   classesnotebookbordertable_idrender_linksr]   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)rO  rQ  rR  rS  rY   r   )Zpandas.io.formats.htmlrT  rU  rI  r   save_to_buffer)ra   rY   r   rO  rP  rQ  rR  rS  rT  rU  ZKlassZhtml_formatterstringrb   rb   rc   to_html  s    "zDataFrameRenderer.to_htmlr   )rY   r   r   r]   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   rV  )Zpandas.io.formats.stringrZ  rI  r   rW  )ra   rY   r   r   rZ  Zstring_formatterrX  rb   rb   rc   r   5  s    zDataFrameRenderer.to_string,winfer"Tstrictz7FilePath | WriteBuffer[bytes] | WriteBuffer[str] | NonerV   zSequence[Hashable] | NonezIndexLabel | Noner@   zStorageOptions | None)path_or_bufr   sepr   index_labelr   compressionr`   	quotecharlineterminator	chunksizedate_formatdoublequote
escapecharerrorsstorage_optionsr]   c                 C  s   ddl m} |du r d}t }nd}|||
||||||||||	||||| jd}|  |r~t|tsjJ | }|  |S dS )z;
        Render dataframe as comma-separated file.
        r   )CSVFormatterNTF)r`  re  ra  r   rj  rc  r`   r  rb  r   rf  rd  rg  rh  ri  rk  r3  )Zpandas.io.formats.csvsrl  r   rI  saver   getvalueclose)ra   r`  r   ra  r   rb  r   rc  r`   rd  re  rf  rg  rh  ri  rj  rk  rl  Zcreated_bufferZcsv_formattercontentrb   rb   rc   to_csvO  s>    zDataFrameRenderer.to_csv)NNNFNNF)NNN)NNr[  NNr\  r]  Nr^  NNNTNr_  N)r   r   r   rK  rd   rY  r   rq  rb   rb   rb   rc   rM    s>          5                   rM  rV   rN  r   )rX  rY   r   r]   c                 C  sZ   t ||d:}||  |du r6| W  d   S W d   dS 1 sL0    Y  dS )zQ
    Perform serialization. Write to buf or return as string if buf is None.
    )r   N)
get_bufferwritern  )rX  rY   r   frb   rb   rc   rW    s
    
rW  zIGenerator[WriteBuffer[str], None, None] | Generator[StringIO, None, None])rY   r   r]   c                 c  s   | durt | } nt } |du r&d}nt| ts8tdt| drJ| V  nVt| trtt|  t| d|dd}|V  W d   q1 s0    Y  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.rs  r\  r_   )r   newlinez1buf is not a file name and it has no write method)	r:   r   r   rV   r  hasattrr9   open	TypeError)rY   r   rt  rb   rb   rc   rr    s    



&rr  rS   rK   r   Tr   r5  r   r   zstr | int | Noner   rm   )r~   r3  rn   r[   digitsr   rM   r   r   r`   fallback_formatterr]   c                 C  s   t | jdrt}ndt| jtr&t}nRt | jdr:t}n>t| jtrLt	}n,t | jdr`t
}nt | jdrtt}nt}|du rd}|du rtd}|du rtd}|| |||||||||	|
d	}| S )
a{  
    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.
    fallback_formatter

    Returns
    -------
    List[str]
    MmZfciuN   r   display.precision)
ry  r[   rn   r3  r   rM   r   r   r`   rz  )r   Zis_np_dtyper   Datetime64Formatterr   r(   Datetime64TZFormatterTimedelta64Formatterr)   ExtensionArrayFormatterFloatArrayFormatterIntArrayFormatterGenericArrayFormatterr   
get_result)r~   r3  rn   r[   ry  r   rM   r   r   r`   rz  Z	fmt_klassZfmt_objrb   rb   rc   ro     sB    )ro   c                   @  sP   e Zd Zdd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     NrS   r~  rK   r   Tr   r   r5  rV   r4  r   r   rU   r   rW   )r~   ry  r3  r[   r   rn   rM   r   r`   fixed_widthr   rz  r]   c                 C  sL   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _d S r   )r~   ry  r[   r   r3  rn   rM   r   r`   r  r   rz  )ra   r~   ry  r3  r[   r   rn   rM   r   r`   r  r   rz  rb   rb   rc   rd     s    zGenericArrayFormatter.__init__rm   re   c                 C  s   |   }t|| jS r   )_format_stringsr.  rM   )ra   r}   rb   rb   rc   r  0  s    z GenericArrayFormatter.get_resultc                   s  j d u r0td}|d u r6tdfdd}nj }jd urHj n6jd urZj n$jd uoljtk}ttj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 u r| }g }t|D ]\}	}
||	 r jd ur<|r<|d||
  nD||	 rV|||
 n*|du rfd}nd}||j||
d q|S )Nr   r  c                   s   t | d ddS )Nz .drt  )_trim_zeros_single_floatr=  )	precisionrb   rc   <lambda>9  s   z7GenericArrayFormatter._format_strings.<locals>.<lambda>r   )r   quote_stringsc              	     s   j d urtt| rtt| rtz<| d u r*W dS | tu r<ttW S | tu sNt| rTW dS W n tt	fyl   Y n0 j S t
| trt| S t
| trt| S t | S d S )NrW   r   )r[   r&   r*   r   rV   r   npZisnatrx  r  r   r0   r/   reprr=  )r3  ra   rb   rc   _formatK  s     



z6GenericArrayFormatter._format_strings.<locals>._formatTZextract_numpyz<ExtensionArray formatting should use ExtensionArrayFormatterr   r#  r8  Fz{v}z {v}rB  )rn   r   r3  rz  r`   r	   r   r;   r   r1   r~   r   r  ndarrayrx  r   Z	map_inferr"   r
  r+   r%  rangeri   shaper   r   r,  r|   r   )ra   rn   r  r  valsinferredZis_float_typer   r}   rv   rB  Ztplrb   )r3  r  ra   rc   r  4  sR    


 

z%GenericArrayFormatter._format_strings)r  NrS   r~  NrK   r   NTTN)r   r   r   rd   r  r  rb   rb   rb   rc   r    s              (r  c                      sR   e Zd Zdd 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  rW   re   c                   sH   t  j|i | | jd urD| jd u rDd| _t| jrD| j| _d | _d S )NF)r   rd   rn   r3  r  callable)ra   argsr   r   rb   rc   rd     s    
zFloatArrayFormatter.__init__Nr   zfloat | Noner   )rn   	thresholdr]   c                   sl   du rj r"fdd nfdd jdkrH fddn du rXS fdd	}|S )
z;Returns a function to be applied on each value to format itNc                   s$    d usJ t | r | dS jS )Nvalue)r+   r[   r  )rn   ra   rb   rc   base_formatter  s
    z<FloatArrayFormatter._value_formatter.<locals>.base_formatterc                   s   t | rt| S  jS r   )r+   rV   r[   r  rq   rb   rc   r    s    r   c                   s    |  djdS )Nr   r   )replacer   r  )r  ra   rb   rc   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        )r+   absr[   r  )r  ra   r  rb   rc   r3    s
    
z7FloatArrayFormatter._value_formatter.<locals>.formatter)rn   r   )ra   rn   r  r3  rb   )r  r  rn   ra   r  rc   _value_formatter  s    
	z$FloatArrayFormatter._value_formatter
np.ndarrayc           
        sl  dddddddddddd j d	ur@jj jS jrPtd
nd	 fdd}jd	u rjrjdu rd}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k }|dj	  k |dk@  }	|	s:|rh|rhjdu rLd}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   rV   )r~   r3  r[   c                   s<   t | }t fddt|  | D | j}|S )Nc                   s    g | ]\}}|s |nqS rb   rb   )ru   valr|  r3  r[   rb   rc   rw     s   zWFloatArrayFormatter.get_result_as_array.<locals>.format_with_na_rep.<locals>.<listcomp>)r*   r  arrayr  ravelreshaper  )r~   r3  r[   mask	formattedrb   r  rc   format_with_na_rep  s    zCFloatArrayFormatter.get_result_as_array.<locals>.format_with_na_repc                 S  s   t |  }t |  }t|t| }}g }t|  ||||D ]\}}	}
}}|sl|sl||| qF|s|||	 d| d qF|s||
 }|dr|| | d q|| d| d qF|| d| d qFt 	|
| jS )N+j-)r  realr  imagr*   r  r|   rs   
startswithr  r  r  )r~   r3  r[   Zreal_valuesZimag_valuesZ	real_maskZ	imag_maskZformatted_lstr  Zreal_valZimag_valZre_isnaZim_isnaZimag_formattedrb   rb   rc   format_complex_with_na_rep  s,    
zKFloatArrayFormatter.get_result_as_array.<locals>.format_complex_with_na_repNzdisplay.chop_thresholdc                   s    | }jdkr dj nj}j}t|}|rF |||}n|||}jr|rjt|j}nt|j}t	j
|ddS |S )NrJ   r8  objectr   )r  rM   r[   r~   r!   r  _trim_zeros_complexr   _trim_zeros_floatr  asarray)rn   r3  r[   r~   Z
is_complexr   r  r  ra   r  rb   rc   format_values_with  s    zCFloatArrayFormatter.get_result_as_array.<locals>.format_values_withTz{value: .{digits:d}f}z{value:.{digits:d}f})ry  c                   s
    j |  S r   )rn   r  rq   rb   rc   r  &  rx   z9FloatArrayFormatter.get_result_as_array.<locals>.<lambda>r   c                 s  s   | ]}t |V  qd S r   r   r   rb   rb   rc   r   2  rx   z:FloatArrayFormatter.get_result_as_array.<locals>.<genexpr>   Fg    .A
   z{value: .{digits:d}e}z{value:.{digits:d}e})r3  r~   r[   r  r   rn   r   r   r   ry  ri   r0  r  r  r   )
ra   r  Zfmt_strrn   Zformatted_valuesmaxlenZtoo_longZabs_valsZhas_large_valuesZhas_small_valuesrb   r  rc   get_result_as_array  sB    




z'FloatArrayFormatter.get_result_as_arrayrm   c                 C  s   t |  S r   )r$  r  rq   rb   rb   rc   r  H  s    z#FloatArrayFormatter._format_strings)NN)r   r   r   rd   r  r  r  r   rb   rb   r   rc   r    s     8 r  c                   @  s   e Zd ZddddZdS )r  rm   re   c                   s>   | j du 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=  rb   rb   rc   r  O  rx   z3IntArrayFormatter._format_strings.<locals>.<lambda>c                 S  s   | dj | dS )Nz dr=  r  r=  rb   rb   rc   r  Q  rx   c                   s   g | ]} |qS rb   rb   r   r3  rb   rc   rw   S  rx   z5IntArrayFormatter._format_strings.<locals>.<listcomp>)r   r3  r~   )ra   Zformatter_strr}   rb   r  rc   r  M  s    


z!IntArrayFormatter._format_stringsNr   r   r   r  rb   rb   rb   rc   r  L  s   r  c                      s8   e Zd Zdddddd fddZd	d
ddZ  ZS )r  r   Nz3np.ndarray | Series | DatetimeIndex | DatetimeArrayrV   rW   )r~   nat_reprg  r]   c                   s$   t  j|fi | || _|| _d S r   )r   rd   r  rg  )ra   r~   r  rg  r   r   rb   rc   rd   X  s    zDatetime64Formatter.__init__rm   re   c                   sZ    j }t|tst|} jdu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 rb   r  r   rq   rb   rc   rw   k  rx   z7Datetime64Formatter._format_strings.<locals>.<listcomp>)r[   rg  )
r~   r   r6   r3  r  _dataZ_format_native_typesr  rg  tolist)ra   r~   r}   rb   rq   rc   r  c  s    
z#Datetime64Formatter._format_strings)r   Nr   r   r   rd   r  r   rb   rb   r   rc   r  W  s     r  c                   @  s   e Zd ZddddZdS )r  rm   re   c                 C  s|   t | jdd}| j}d }|d u r,|jdd}t|tr@| }n
t|}t	||| j
| j| j| j| j| j| j| j|d}|S )NTr  )Zboxed)	rn   r[   ry  r   rM   r   r   r`   rz  )r1   r~   r3  
_formatterr   r,   rp   r  r  ro   rn   r[   ry  r   rM   r   r   r`   )ra   r~   r3  rz  r  r}   rb   rb   rc   r  t  s,    


z'ExtensionArrayFormatter._format_stringsNr  rb   rb   rb   rc   r  s  s   r  znp.ndarray | Sequence[float])percentilesr]   c                 C  s@  t | } t| r.t | dkr.t | dks6tdd|  } |  t}t || }t |rz|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   z/percentiles should all be in the interval [0,1]d   c                 S  s   g | ]}|d  qS %rb   rt   rb   rb   rc   rw     rx   z&format_percentiles.<locals>.<listcomp>N)to_beginto_endr  c                 S  s   g | ]}|d  qS r  rb   rt   rb   rb   rc   rw     rx   )r  r  r%   r
  r  roundastyper   iscloserV   uniquefloorlog10r   Zediff1dr0  Z
empty_liker  )r  Zpercentiles_round_typeZint_idxoutZunique_pctsr  r  precrb   rb   rc   format_percentiles  s6    "




r  z2np.ndarray | DatetimeArray | Index | DatetimeIndexrU   r~   r]   c                 C  s~   t | ts|  } t | ttfs(t| } | jd ur6dS | j}|tk}t| j	}t
|}t||| dk dk}|rzdS dS )NFr   T)r   r2   r  r-   r6   tzZasi8r   r   r   r   r  logical_andr   )r~   
values_intconsider_valuesZresoZppd	even_daysrb   rb   rc   is_dates_only  s    


r  r   zNaTType | Timestamp)r   r  r]   c                 C  s   | t u r|S t| S r   )r   rV   )r   r  rb   rb   rc   _format_datetime64  s    r  )r   r  rg  r]   c                 C  s&   t | tr|S |r| |S | jS d S r   )r   r    strftimeZ
_date_repr)r   r  rg  rb   rb   rc   _format_datetime64_dateonly  s
    

r  r   )is_dates_only_r  rg  r]   c                   s"   | r fddS fddS dS )z]Return a formatter callable taking a datetime64 as input and providing
    a string as outputc                   s   t |  dS )N)r  rg  )r  r=  rg  r  rb   rc   r    s   z'get_format_datetime64.<locals>.<lambda>c                   s   t |  dS )Nr  )r  r=  r  rb   rc   r    rx   Nrb   )r  r  rg  rb   r  rc   get_format_datetime64  s    r  z*np.ndarray | DatetimeArray | DatetimeIndex)r~   rg  r]   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~   rg  idorb   rb   rc   !get_format_datetime64_from_values  s    r  c                   @  s   e Zd ZddddZdS )r  rm   re   c                   s@   t | j}| jt}| jp(t|| jd  fdd|D }|S )zwe by definition have a TZ)rg  c                   s   g | ]} |qS rb   rb   r   r  rb   rc   rw   .  rx   z9Datetime64TZFormatter._format_strings.<locals>.<listcomp>)r  r~   r  r  r3  r  rg  )ra   r  r~   r}   rb   r  rc   r  '  s    
z%Datetime64TZFormatter._format_stringsNr  rb   rb   rb   rc   r  &  s   r  c                      s8   e Zd Zdddddd fdd	Zd
dddZ  ZS )r  r   Fznp.ndarray | TimedeltaIndexrV   rU   rW   r~   r  boxr]   c                   s$   t  j|fi | || _|| _d S r   )r   rd   r  r  )ra   r~   r  r  r   r   rb   rc   rd   4  s    zTimedelta64Formatter.__init__rm   re   c                   s.   | j pt| j| j| jd  fdd| jD S )N)r  r  c                   s   g | ]} |qS rb   rb   r   r  rb   rc   rw   C  rx   z8Timedelta64Formatter._format_strings.<locals>.<listcomp>)r3  get_format_timedelta64r~   r  r  rq   rb   r  rc   r  ?  s    z$Timedelta64Formatter._format_strings)r   Fr  rb   rb   r   rc   r  3  s     r  Fz,np.ndarray | TimedeltaIndex | TimedeltaArrayzstr | floatr  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
    l     "R: r   Nlongc                   sN   | d u st | rt| rS t| ts.t| } | jd} rJd| d}|S )Nr  ')r&   r*   r   r   Z
_repr_base)r   r   r  r   r  rb   rc   r  e  s    
z*get_format_timedelta64.<locals>._formatter)viewr  int64r   r  r   )
r~   r  r  r  r  Zone_day_nanosZnot_midnightZbothr  r  rb   r  rc   r  F  s    r  zTextAdjustment | None)r(  rM   r)  r   r]   c                   s   t | dks|dkr| S |d u r(t  n| t fdd| D |d urTt|tdd u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   )
adjustmentrb   rc   r     rx   z$_make_fixed_width.<locals>.<genexpr>r   rV   )r   r]   c                   s6   d ur2dk  | k@ r2| d d  d } | S )Nr   r   r   r=  )r  conf_maxr   rb   rc   just  s    z_make_fixed_width.<locals>.justc                   s   g | ]} |qS rb   rb   r   )r  rb   rc   rw     rx   z%_make_fixed_width.<locals>.<listcomp>r   )ri   r   r0  r   rM   )r(  rM   r)  r   r   rb   )r  r  r  r   rc   r.  u  s    
r.  r  )str_complexesr   r]   c           	        s   g g  }}| D ]@}t d|}|d|dd  |d|dd  qt| }t|| |}t|dkrvg S tdd |D d	   fd
dt|d| ||d D }|S )z
    Separates the real and imaginary parts from the complex number, and
    executes the _trim_zeros_float method on each of those.
    z([j+-])r_   Nr   c                 s  s   | ]}t |V  qd S r   r   )ru   partrb   rb   rc   r     rx   z&_trim_zeros_complex.<locals>.<genexpr>r   c                   s6   g | ].\}}||d   |dd d   d qS )r   r   N>r  rb   )ru   Zreal_ptZimag_ptZpadded_lengthrb   rc   rw     s   z'_trim_zeros_complex.<locals>.<listcomp>)rerG  r|   r{   ri   r  r0  r  )	r  r   Z	real_partZ	imag_partr   trimmednZpadded_partspaddedrb   r  rc   r    s    

r  )	str_floatr]   c                 C  s    |  d} | dr| d7 } | S )zX
    Trims trailing zeros after a decimal point,
    leaving just one if necessary.
    0r   )rstripendswith)r  rb   rb   rc   r    s    

r  np.ndarray | list[str])
str_floatsr   r]   c                   sp   | }t d  dddfdddddfd	d
}||rXfdd|D }q< 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]*$rU   re   c                   s   t  | d uS r   )r  matchr=  )number_regexrb   rc   is_number_with_decimal  s    z1_trim_zeros_float.<locals>.is_number_with_decimalr  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 rb   rb   r   r  rb   rc   rw     rx   z:_trim_zeros_float.<locals>.should_trim.<locals>.<listcomp>r   c                 s  s   | ]}| d V  qdS )r  Nr   r   rb   rb   rc   r     rx   z9_trim_zeros_float.<locals>.should_trim.<locals>.<genexpr>)ri   r
  )r~   Znumbersr  rb   rc   should_trim  s    z&_trim_zeros_float.<locals>.should_trimc                   s$   g | ]} |r|d d n|qS )Nr  rb   r   r  rb   rc   rw     rx   z%_trim_zeros_float.<locals>.<listcomp>c                   s*   g | ]"}|r"|  r"|d  n|qS )r  r  r   )r   r  rb   rc   rw     s   )r  compile)r  r   r  r  r   rb   )r   r  r  rc   r    s    r  r2   )r   r]   c                 C  s$   t | trtj| j S | jd uS d S r   )r   r3   comZany_not_noner   r   )r   rb   rb   rc   r    s    
r  c                   @  s\   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dZddddd ZdS )"EngFormatterzl
    Formats float values according to engineering format.

    Based on matplotlib.ticker.EngFormatter
    r9  zart  pr  ur|  r_   rA  r{  GTPEZY)iiiiiiir   r   r  	   r~              NFr   rU   rW   accuracyuse_eng_prefixr]   c                 C  s   || _ || _d S r   r  r  )ra   r  r  rb   rb   rc   rd     s    zEngFormatter.__init__floatrV   )numr]   c           
      C  s  t t|}t |rdS t |r(dS d}|dk r>d}| }|dkrft 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u 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
        rS   infr   r   r  r   zE-Z02dzE+r  Nz{mant: g}{prefix}z{mant: .r  z
f}{prefix})mantprefix)r   rV   is_nanis_infiniter   mathr  r  r   r0  ENG_PREFIXESr  r  r  r   )
ra   r!  ZdnumsignZpow10Z	int_pow10r$  r#  Z
format_strr  rb   rb   rc   __call__  s4    

 
zEngFormatter.__call__)NF)r   r   r   rK  r(  rd   r*  rb   rb   rb   rc   r    s,    r  r   r   rW   r  c                 C  s   t dt| | dS )a  
    Format float representation in DataFrame with SI notation.

    Parameters
    ----------
    accuracy : int, default 3
        Number of decimal digits after the floating point.
    use_eng_prefix : bool, default False
        Whether to represent a value with SI prefixes.

    Returns
    -------
    None

    Examples
    --------
    >>> df = pd.DataFrame([1e-9, 1e-3, 1, 1e3, 1e6])
    >>> df
                  0
    0  1.000000e-09
    1  1.000000e-03
    2  1.000000e+00
    3  1.000000e+03
    4  1.000000e+06

    >>> pd.set_eng_float_format(accuracy=1)
    >>> df
             0
    0  1.0E-09
    1  1.0E-03
    2  1.0E+00
    3  1.0E+03
    4  1.0E+06

    >>> pd.set_eng_float_format(use_eng_prefix=True)
    >>> df
            0
    0  1.000n
    1  1.000m
    2   1.000
    3  1.000k
    4  1.000M

    >>> pd.set_eng_float_format(accuracy=1, use_eng_prefix=True)
    >>> df
          0
    0  1.0n
    1  1.0m
    2   1.0
    3  1.0k
    4  1.0M

    >>> pd.set_option("display.float_format", None)  # unset option
    r   N)r   r  r  rb   rb   rc   set_eng_float_formatO  s    7r+  r_   zbool | object | strzlist[dict[int, int]])r?  sentinelr]   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)ri   r,  r|   )	r?  r,  controlr   r7  
last_indexlengthsrv   keyrb   rb   rc   get_level_lengths  s     r1  zWriteBuffer[str])rY   linesr]   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   rV   r   rb   rb   rc   r     rx   z#buffer_put_lines.<locals>.<genexpr>c                 S  s   g | ]}t |qS rb   rE  r   rb   rb   rc   rw     rx   z$buffer_put_lines.<locals>.<listcomp>rh   N)r   rs  r{   )rY   r2  rb   rb   rc   buffer_put_lines  s    r3  )NN)N)	NrS   NNrK   r   TNN)r   )r   N)r   N)r   F)rK   NN)r   )r   )r   F)r_   )rK  
__future__r   collections.abcr   r   r   r   r   
contextlibr   csvr	   r
   r   r   	functoolsr   ior   r'  r  shutilr   typingr   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   r   r   Zpandas._libs.tslibs.nattyper    Zpandas.core.dtypes.commonr!   r"   r#   r$   r%   r&   Zpandas.core.dtypes.dtypesr'   r(   r)   Zpandas.core.dtypes.missingr*   r+   Zpandas.core.arraysr,   r-   r.   Zpandas.core.arrays.string_r/   Zpandas.core.baser0   Zpandas.core.commoncorecommonr
  Zpandas.core.constructionr1   Zpandas.core.indexes.apir2   r3   r4   r5   Zpandas.core.indexes.datetimesr6   Zpandas.core.indexes.timedeltasr7   Zpandas.core.reshape.concatr8   Zpandas.io.commonr9   r:   r   r;   Zpandas._typingr<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   ZpandasrG   rH   rI   __annotations__Z_VALID_JUSTIFY_PARAMETERSrQ   rR   r   r   r   r   r   r   r   rM  rW  rr  ro   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r.  r  r  r  r  r  r+  r1  r3  rb   rb   rb   rc   <module>   s      4;	@ !'!&   C     (         &Rp JE     1   "! $`; +