a
    OfO                    @  s`  U d 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 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 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( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z= ddl>m?Z? ddl@mAZA dd	lBmC  mDZE ddlFmGZGmHZHmIZImJZJ ddlKmLZL ddlMmNZN ddlOmPZP ddlQmRZRmSZS ddlTmUZU erddlVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZb ddlcmdZdmeZe dZfd egd!< d"Zhd#Zid egd$< G d%d& d&Zjd'd(d)d*Zkd'd(d+d,ZlG d-d. d.ZmG d/d0 d0Zndd1d2d3d3d4d5d6Zoe	dd2d3d7d8d9d:Zpdd?d@dAd1dBdCd1d1dDdBd@dEdFdGdHZqG dIdJ dJZrG dKdL dLerZsG dMdN dNerZtG dOdP dPerZuG dQdR dRerZvdSdEdTdUdVZwdSdWdXdYdZZxdd\d1d1d]d^d_Zydd\d1d3d1d`dadbZzddcd1d3dddedfdgZ{G dhdi dieuZ|G djdk dkerZ}ddmdndcdddodpdqZ~ddEd1dBdrdEdsdtduZdd?d1dEdvdwdxZd1d1dydzd{Zdd|d1dEd}d~dZddcdddZG dd dZddWdcddddZdddddddZddEdd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MappingSequence)contextmanager)
QUOTE_NONE)Decimal)partial)StringION)get_terminal_size)TYPE_CHECKINGAnyCallableFinalcast)
get_option
set_option)lib)NA)NaT	Timedelta	Timestamp)NaTType)is_complex_dtypeis_float
is_integeris_list_likeis_numeric_dtype	is_scalar)CategoricalDtypeDatetimeTZDtypeExtensionDtype)isnanotna)CategoricalDatetimeArrayExtensionArrayTimedeltaArray)StringDtype)PandasObject)Index
MultiIndexPeriodIndexensure_index)DatetimeIndex)TimedeltaIndex)concat)check_parent_directorystringify_path)printing)	ArrayLikeAxesColspaceArgTypeColspaceTypeCompressionOptionsFilePathFloatFormatTypeFormattersType
IndexLabelSequenceNotStr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``.
        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endinheritzmatch-parentinitialZunsetz
        Returns
        -------
        str or None
            If buf is None, returns the result as a string. Otherwise returns
            None.
    return_docstringc                   @  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	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S )SeriesFormatterz\
    Implement the main logic of Series.to_string, which underlies
    Series.__repr__.
    TNaNFN)	lengthheaderindexna_repnamefloat_formatdtypemax_rowsmin_rowsrB   
bool | strboolstr
str | None
int | NoneNone)seriesrO   rP   rQ   rR   rS   rT   rU   rV   rW   returnc       	         C  sj   || _ t | _|| _|| _|| _|| _|| _|	| _|
| _	|d u rHt
d}|| _|| _t | _|   d S )Ndisplay.float_format)r^   r   bufrS   rR   rP   rO   rQ   rV   rW   r   rT   rU   r4   get_adjustmentadj_chk_truncate)selfr^   rO   rP   rQ   rR   rS   rT   rU   rV   rW    rf   Q/var/www/ai-form-bot/venv/lib/python3.9/site-packages/pandas/io/formats/format.py__init__   s    
zSeriesFormatter.__init__r_   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      )rW   rV   lenr^   r   intminilocr1   
tr_row_num	tr_seriesis_truncated_vertically)re   rW   rV   rr   r^   row_numrf   rf   rg   rd      s$    

"zSeriesFormatter._chk_truncatec                 C  s4  | j j}d}| j j}t|tttfr>|jd ur>|d|j 7 }| jdurx|d urx|r\|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rt| jjdd }|r|r|d7 }|dt	
| 7 }t| jjtr,| jj }|r$|d7 }||7 }t|S )N zFreq: Fz, 	
)escape_charszName: TtruncatezLength: rS   zdtype: rx   )r^   rS   rQ   
isinstancer/   r-   r0   freqZfreqstrr4   pprint_thingrO   rr   rl   rU   getattrrq   r    _valuesZ_get_repr_footerrZ   )re   rS   footerrQ   Zseries_nameZ
dtype_nameZ
level_inforf   rf   rg   _get_footer   sB    
zSeriesFormatter._get_footer	list[str]c                 C  s   t | jjd | j| j| jdS )N)rT   rR   leading_space)format_arrayrq   r   rT   rR   rQ   re   rf   rf   rg   _get_formatted_values(  s    z%SeriesFormatter._get_formatted_valuesc                 C  s~  | j }|  }t|dkr2t| jj d| dS |j}t|}t|t	rz|j
dd d}t }|jdg|R  d}n|jdd}|  }| jrd}| j}	tt|	}	| j||	d	  }
|
d
krd}nd}| jj|g|
ddd }||	| | ||	d	 d | jr2| jjd
g|d	d  |gR  }n| jd
|}| jr^|r^|d d | }|rp|d| 7 }td|S )Nr   z([], )T)include_namessparsifyrk   rx   include_namerj      ...z..rF   modert   )rq   r   rl   typer^   __name__rQ   
_has_namesr{   r,   _format_multir4   rb   adjoinsplit_format_flatr   rr   rp   r   rm   rc   rG   insertrP   rZ   join)re   r^   r   rQ   Zhave_header	fmt_indexrc   
fmt_valuesZn_header_rowsrs   widthZdot_strresultrf   rf   rg   	to_string1  s>    

"zSeriesFormatter.to_string)	r   
__module____qualname____doc__rh   rd   r   r   r   rf   rf   rf   rg   rM      s   	& *	rM   zdict[str, Any]ri   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)rV   rW   max_colsZmax_colwidthshow_dimensions
line_width)pandas.io.formatsr   r   Zget_console_size)r   r   _rf   rf   rg   get_dataframe_repr_params_  s    r   c                  C  sJ   t  \} }td}|dkr|n|}|dkr.|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   )rS   rU   rW   rV   rO   )r   r   )r   heightZmax_rows_optrV   rW   rf   rf   rg   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.

    Used by DataFrame.to_string, which backs DataFrame.__repr__.
    rt   NTrN   F.rA   zAxes | NonezColspaceArgType | Nonezbool | SequenceNotStr[str]rY   rZ   zFormattersType | Noner[   FloatFormatType | Nonebool | Noner\   rX   r]   )framecolumns	col_spacerP   rQ   rR   
formattersrG   rT   r   index_namesrV   rW   r   r   decimal	bold_rowsescaper_   c                 C  s   || _ | || _| || _|| _|| _|| _| || _	| 
|| _|	| _| |
| _|| _|| _|| _|| _|| _|| _|| _|| _|  | _|  | _| j | _|   t | _d S N) r   _initialize_columnsr   _initialize_colspacer   rP   rQ   rR   _initialize_formattersr   _initialize_justifyrG   rT   _initialize_sparsifyr   show_index_namesr   r   r   rV   rW   r   r   _calc_max_cols_fittedmax_cols_fitted_calc_max_rows_fittedmax_rows_fittedtr_framerz   r4   rb   rc   )re   r   r   r   rP   rQ   rR   r   rG   rT   r   r   rV   rW   r   r   r   r   r   rf   rf   rg   rh     s.    

zDataFrameFormatter.__init__zlist[list[str]]ri   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_indexrQ   _get_formatted_indexr   r   )re   strcolsZ	str_indexrf   rf   rg   get_strcols  s
    zDataFrameFormatter.get_strcolsc                 C  s   | j du p| j dko| jS )NTrz   )r   is_truncatedr   rf   rf   rg   should_show_dimensions  s    
z)DataFrameFormatter.should_show_dimensionsc                 C  s   t | jp| jS r   )rY   is_truncated_horizontallyrr   r   rf   rf   rg   r     s    zDataFrameFormatter.is_truncatedc                 C  s   t | jot| j| jkS r   )rY   r   rl   r   r   rf   rf   rg   r     s    z,DataFrameFormatter.is_truncated_horizontallyc                 C  s   t | jot| j| jkS r   )rY   r   rl   r   r   rf   rf   rg   rr     s    z*DataFrameFormatter.is_truncated_verticallyc                 C  s    dt | j dt | jj dS )Nz

[z rows x z	 columns])rl   r   r   r   rf   rf   rg   dimensions_info  s    z"DataFrameFormatter.dimensions_infoc                 C  s   t | jjS r   )r   r   rQ   r   rf   rf   rg   has_index_names  s    z"DataFrameFormatter.has_index_namesc                 C  s   t | jjS r   )r   r   r   r   rf   rf   rg   has_column_names  s    z#DataFrameFormatter.has_column_namesc                 C  s   t | j| j| jfS r   )allr   rQ   r   r   rf   rf   rg   show_row_idx_names  s    z%DataFrameFormatter.show_row_idx_namesc                 C  s   t | j| j| jfS r   )r   r   r   rP   r   rf   rf   rg   show_col_idx_names  s    z%DataFrameFormatter.show_col_idx_namesrm   c                 C  s   t | jpt| jt| jS r   )rn   rV   rl   r   r   rf   rf   rg   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   )re   r   rf   rf   rg   r     s    z'DataFrameFormatter._initialize_sparsifyr<   )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   )rl   r   r   r{   dict
ValueError)re   r   rf   rf   rg   r     s    
z)DataFrameFormatter._initialize_formatters)rG   r_   c                 C  s   |d u rt dS |S d S )Nzdisplay.colheader_justifyr   )re   rG   rf   rf   rg   r      s    z&DataFrameFormatter._initialize_justifyr+   )r   r_   c                 C  s,   |d ur t |}| j| | _|S | jjS d S r   )r.   r   r   )re   r   colsrf   rf   rg   r   &  s
    z&DataFrameFormatter._initialize_columnsr8   )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 )Nrt   c                   s   i | ]
}| qS rf   rf   ).0columnr   rf   rg   
<dictcomp>5      z;DataFrameFormatter._initialize_colspace.<locals>.<dictcomp>z,Col_space is defined for an unknown column: zCol_space length(r   r   )r{   rm   rZ   updater   r   r   keysr   rl   r   zip)re   r   r   r   rf   r   rg   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)re   r   r   rf   rf   rg   r   F  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   rV   _get_number_of_auxiliary_rows_is_screen_short_adjust_max_rows)re   r   r   rV   rf   rf   rg   r   Q  s    


z(DataFrameFormatter._calc_max_rows_fitted)rV   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
        )rl   r   rW   rn   )re   rV   rf   rf   rg   r   d  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   )rY   r   rV   r   rf   rf   rg   r   r  s    z"DataFrameFormatter._is_in_terminalc                 C  s   t | jdkot| jj|kS Nr   )rY   r   rl   r   r   )re   	max_widthrf   rf   rg   r   v  s    z$DataFrameFormatter._is_screen_narrowc                 C  s   t | jdkot| j|kS r   )rY   rV   rl   r   )re   
max_heightrf   rf   rg   r   y  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.rj   )r   rl   r   
splitlinesrP   )re   Zdot_rowZ
prompt_rowZnum_rowsrf   rf   rg   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_horizontallyrr   _truncate_verticallyr   rf   rf   rg   rz     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
        Nrk   rj   Zaxis)r   r   ro   r1   r{   r   listtupler   rm   r   Z
tr_col_num)re   Zcol_numrD   rE   rf   rf   rg   r     s    
z)DataFrameFormatter._truncate_horizontallyc                 C  s   | j dusJ | j d }|dkrZt| j}tt|t|| |g}| jj| | _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
        Nrk   rj   )r   rl   r   npZhstackZarangero   r   rm   rV   rp   )re   rs   _lenZ_slicerf   rf   rg   r     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   )stringsrG   minimumrc   zWriting z cols but got z aliasesc                 S  s   g | ]
}|gqS rf   rf   )r   labelrf   rf   rg   
<listcomp>  r   zADataFrameFormatter._get_strcols_without_index.<locals>.<listcomp>rt   c                 3  s   | ]} j |V  qd S r   rc   rl   r   xr   rf   rg   	<genexpr>  r   z@DataFrameFormatter._get_strcols_without_index.<locals>.<genexpr>)r   rc   c                 3  s   | ]} j |V  qd S r   r   r   r   rf   rg   r     r   r   )r   rP   	enumerater   
format_col_make_fixed_widthrG   rm   r   getrc   appendr   r   rZ   rl   r   r   _get_formatted_column_labelsr   max)
re   r   icr   str_columnsr   ZcheaderZheader_colwidthmax_lenrf   r   rg   r     sP    


 z-DataFrameFormatter._get_strcols_without_indexr   )r   r_   c              	   C  sL   | j }| |}t|jd d |f j|| j| j| j|j	| | j
| jdS )N)rT   rR   spacer   r   )r   _get_formatterr   ro   r   rT   rR   r   r   r   r   rQ   )re   r   r   	formatterrf   rf   rg   r     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   rm   r   r   )re   r   rf   rf   rg   r    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dd}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)r   levelrf   rf   rg   r     r   zBDataFrameFormatter._get_formatted_column_labels.<locals>.<genexpr>c                   s"   |j vr |  rsd| S |S )N )r   )r   y)need_leadsprestrict_formattingre   rf   rg   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 rf   rf   )r   r  )r  r   rf   rg   r      r   zMDataFrameFormatter._get_formatted_column_labels.<locals>.<genexpr>.<listcomp>Nrf   )r   )r  r   rg   r      r   c                 S  s   g | ]}t |qS rf   )r   r   rf   rf   rg   r   %  r   zCDataFrameFormatter._get_formatted_column_labels.<locals>.<listcomp>r   c                   s0   g | ](\}} |s& | r&d | n|gqS )r  )r  )r   r   r   )r  re   rf   rg   r   *  s   )Zpandas.core.indexes.multir	  r   r{   r,   r   r   r   r   dtypesr   anylevelsr   mapr   r   rl   r   r   )re   r   r	  r   Zfmt_columnsr  Zstr_columns_tupler  rf   )r  r  re   r  rg   r     s,    

	z/DataFrameFormatter._get_formatted_column_labelsc                   s   dd j  D  |j}|j}d}t|trJ|jj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 rf   )r   rm   )r   kvrf   rf   rg   r   4  r   z;DataFrameFormatter._get_formatted_index.<locals>.<dictcomp>	__index__)r   r   r  )r   r  c              
     s.   g | ]&}t tt|d  ddjdqS )rD   rt   r   )rG   r   rc   )r   r   r   r   rc   r   r   re   rf   rg   r   D  s   z;DataFrameFormatter._get_formatted_index.<locals>.<listcomp>rj   rx   c                 S  s   g | ]}t |qS rf   rZ   r   rf   rf   rg   r   Q  r   rt   )r   itemsrQ   r   r  r{   r,   r   r   r   r   rc   r   r   r   _get_column_name_listZnlevelsrP   )re   r   rQ   r   fmtr   ZadjoinedZ
col_headerrf   r  rg   r   1  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 )Nrt   rf   )r   rS   rf   rf   rg   r   ^  r   z;DataFrameFormatter._get_column_name_list.<locals>.<genexpr>rt   )r   r   r{   r,   extendnamesr   rS   )re   r  r   rf   rf   rg   r  Z  s    
z(DataFrameFormatter._get_column_name_list)NNTTrN   NNNNTNNNFr   FT)(r   r   r   r   rC   rL   rh   r   propertyr   r   r   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rz   r   r   r   r   r  r   r   r  rf   rf   rf   rg   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   r]   )r  r_   c                 C  s
   || _ d S r   )r  )re   r  rf   rf   rg   rh   u  s    zDataFrameRenderer.__init__NF"FilePath | WriteBuffer[str] | Noner[   zstr | list | tuple | NonerY   zint | bool | None)ra   encoding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)r#  r%  r&  r'  ra   r"  )Zpandas.io.formats.htmlr(  r)  r  r   save_to_buffer)re   ra   r"  r#  r$  r%  r&  r'  r(  r)  ZKlassZhtml_formatterstringrf   rf   rg   to_htmlx  s    "zDataFrameRenderer.to_htmlr\   )ra   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   r*  )Zpandas.io.formats.stringr.  r  r   r+  )re   ra   r"  r   r.  Zstring_formatterr,  rf   rf   rg   r     s    zDataFrameRenderer.to_string,winfer"Tstrictz7FilePath | WriteBuffer[bytes] | WriteBuffer[str] | NonerZ   zSequence[Hashable] | NonezIndexLabel | Noner9   zStorageOptions | None)path_or_bufr"  sepr   index_labelr   compressionquoting	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)r4  r:  r5  r"  r?  r7  r8  r   r6  r   r;  r9  r<  r=  r>  r@  r  )Zpandas.io.formats.csvsrA  r   r  saver{   getvalueclose)re   r4  r"  r5  r   r6  r   r7  r8  r9  r:  r;  r<  r=  r>  r?  r@  rA  Zcreated_bufferZcsv_formattercontentrf   rf   rg   to_csv  s>    zDataFrameRenderer.to_csv)NNNFNNF)NNN)NNr/  NNr0  r1  Nr2  NNNTNr3  N)r   r   r   r   rh   r-  r   rF  rf   rf   rf   rg   r   d  s>          5                   r   rZ   r!  r[   )r,  ra   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writerC  )r,  ra   r"  fdrf   rf   rg   r+    s
    
r+  zIGenerator[WriteBuffer[str], None, None] | Generator[StringIO, None, None])ra   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.rH  r0  rt   )r"  newlinez1buf is not a file name and it has no write method)	r3   r   r{   rZ   r   hasattrr2   open	TypeError)ra   r"  frf   rf   rg   rG    s    



&rG  rN   rE   r   Tr5   r  r   r\   zstr | int | Noner   r   )valuesr  rT   rR   digitsr  rG   r   r   r8  fallback_formatterr_   c                 C  s   t | jdrt}tt| } nxt| jtr:t}tt| } n\t | jdrXt	}tt
| } n>t| jtrjt}n,t | jdr~t}nt | jdrt}nt}|du rd}|du rtd}|du rtd}|| |||||||||	|
d	}| S )
a  
    Format an array for printing.

    Parameters
    ----------
    values : np.ndarray or ExtensionArray
    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._get_values_for_csv), we don't want the
        leading space since it should be left-aligned.
    fallback_formatter

    Returns
    -------
    List[str]
    MmfciuN   r`   display.precision)
rP  rR   rT   r  r  rG   r   r   r8  rQ  )r   Zis_np_dtyperU   _Datetime64Formatterr   r&   r{   r!   _Datetime64TZFormatter_Timedelta64Formatterr(   r"   _ExtensionArrayFormatterFloatArrayFormatter_IntArrayFormatter_GenericArrayFormatterr   
get_result)rO  r  rT   rR   rP  r  rG   r   r   r8  rQ  Z	fmt_klassZfmt_objrf   rf   rg   r   7  sH    )r   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^     NrN   rV  rE   r   Tr5   rm   r  rZ   r  r   r\   rY   r   r]   )rO  rP  r  rR   r  rT   rG   r   r8  fixed_widthr   rQ  r_   c                 C  sL   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _d S r   )rO  rP  rR   r  r  rT   rG   r   r8  ra  r   rQ  )re   rO  rP  r  rR   r  rT   rG   r   r8  ra  r   rQ  rf   rf   rg   rh     s    z_GenericArrayFormatter.__init__r   ri   c                 C  s   |   }t|| jS r   )_format_stringsr   rG   )re   r   rf   rf   rg   r_    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}j	}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r4|r4|d||
  q||	 rN|||
 q|du r^d}nd}||j||
d q|S )Nr`   rW  c                   s   t | d ddS )Nz .drN  )_trim_zeros_single_floatr  )	precisionrf   rg   <lambda>  s   z8_GenericArrayFormatter._format_strings.<locals>.<lambda>ru   )ry   quote_stringsc                   s   j d urvt| rvt| rv| d u r&dS | tu r6ttS t| rRt| rRt| S | t	u slt
| tjtjfrpdS j S t
| trt| S t
| trt| S t | S d S )Nr]   r   )rR   r   r#   r   rZ   r   r   r   isinfr   r{   Z
datetime64Ztimedelta64r*   r)   reprr  )r  re   rf   rg   _format  s    

z7_GenericArrayFormatter._format_strings.<locals>._formatz=ExtensionArray formatting should use _ExtensionArrayFormatterrj   r   r  Fz{v}z {v}r  )rT   r   r  rQ  r8  r   r
   r4   r}   rO  r{   r   ZndarrayrM  r   Z	map_inferr   r   r$   r   rangerl   shaper   r  r   r   format)re   rT   rg  rj  valsinferredZis_float_typer   r   r   r  Ztplrf   )r  re  re   rg   rb    sR    


 

z&_GenericArrayFormatter._format_strings)r`  NrN   rV  NrE   r   NTTN)r   r   r   rh   r_  rb  rf   rf   rf   rg   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\  r]   ri   c                   sH   t  j|i | | jd urD| jd u rDd| _t| jrD| j| _d | _d S )NF)superrh   rT   r  ra  callable)re   argskwargs	__class__rf   rg   rh     s    
zFloatArrayFormatter.__init__Nr   zfloat | Noner   )rT   	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$   rR   rk  )rT   re   rf   rg   base_formatter  s
    z<FloatArrayFormatter._value_formatter.<locals>.base_formatterc                   s   t | rt| S  jS r   )r$   rZ   rR   rk  r   rf   rg   rz  &  s    r   c                   s    |  djdS )Nr   rj   )replacer   rk  )rz  re   rf   rg   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$   absrR   rx  )r|  re   rw  rf   rg   r  4  s
    
z7FloatArrayFormatter._value_formatter.<locals>.formatter)rT   r   )re   rT   rw  r  rf   )rz  r|  rT   re   rw  rg   _value_formatter  s    
	z$FloatArrayFormatter._value_formatterz
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
        r5   r   rZ   )rO  r  rR   c                   s<   t | }t fddt|  | D | j}|S )Nc                   s    g | ]\}}|s |nqS rf   rf   )r   valrS  r  rR   rf   rg   r   H  s   zWFloatArrayFormatter.get_result_as_array.<locals>.format_with_na_rep.<locals>.<listcomp>)r#   r   arrayr   ravelreshaperm  )rO  r  rR   mask	formattedrf   r  rg   format_with_na_repE  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   strip
startswithr  r  rm  )rO  r  rR   Zreal_valuesZimag_valuesZ	real_maskZ	imag_maskZformatted_lstr  Zreal_valZimag_valZre_isnaZim_isnaZimag_formattedrf   rf   rg   format_complex_with_na_repO  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 )NrD   r  objectrU   )r~  rG   rR   rO  r   ra  _trim_zeros_complexr   _trim_zeros_floatr   asarray)rT   r  rR   rO  Z
is_complexr   r  r  re   rw  rf   rg   format_values_withu  s    zCFloatArrayFormatter.get_result_as_array.<locals>.format_values_withTz{value: .{digits:d}f}z{value:.{digits:d}f})rP  c                   s
    j |  S r   )rT   rx  r   rf   rg   rf    r   z9FloatArrayFormatter.get_result_as_array.<locals>.<lambda>r   c                 s  s   | ]}t |V  qd S r   rl   r   rf   rf   rg   r     r   z:FloatArrayFormatter.get_result_as_array.<locals>.<genexpr>   Fg    .A
   z{value: .{digits:d}e}z{value:.{digits:d}e})r  rO  rR   ra  r   rT   r   r
   rn  rP  rl   r   r   r}  r  )
re   r  Zfmt_strrT   Zformatted_valuesmaxlenZtoo_longZabs_valsZhas_large_valuesZhas_small_valuesrf   r  rg   get_result_as_array?  sB    




z'FloatArrayFormatter.get_result_as_arrayr   c                 C  s   t |  S r   )r   r  r   rf   rf   rg   rb    s    z#FloatArrayFormatter._format_strings)NN)r   r   r   rh   r~  r  rb  __classcell__rf   rf   ru  rg   r\    s     8 r\  c                   @  s   e Zd ZddddZdS )r]  r   ri   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 )Nrc  r  rn  r  rf   rf   rg   rf    r   z4_IntArrayFormatter._format_strings.<locals>.<lambda>c                 S  s   | dj | dS )Nz dr  r  r  rf   rf   rg   rf    r   c                   s   g | ]} |qS rf   rf   r   r  rf   rg   r     r   z6_IntArrayFormatter._format_strings.<locals>.<listcomp>)r   r  rO  )re   Zformatter_strr   rf   r  rg   rb    s    


z"_IntArrayFormatter._format_stringsN)r   r   r   rb  rf   rf   rf   rg   r]    s   r]  c                      sB   e Zd ZU ded< dddddd fdd	Zd
dddZ  ZS )rX  r&   rO  r   NrZ   r]   )rO  nat_repr<  r_   c                   s$   t  j|fi | || _|| _d S r   )rq  rh   r  r<  )re   rO  r  r<  rt  ru  rf   rg   rh     s    z_Datetime64Formatter.__init__r   ri   c                   s<    j } jdur" fdd|D S |j j jd}| S )z&we by definition have DO NOT have a TZNc                   s   g | ]}  |qS rf   r  r   r   rf   rg   r     r   z8_Datetime64Formatter._format_strings.<locals>.<listcomp>)rR   r<  )rO  r  Z_format_native_typesr  r<  tolist)re   rO  r   rf   r   rg   rb    s    
z$_Datetime64Formatter._format_strings)r   Nr   r   r   __annotations__rh   rb  r  rf   rf   ru  rg   rX    s
   
  rX  c                   @  s$   e Zd ZU ded< ddddZdS )r[  r'   rO  r   ri   c                 C  sx   | j }| j}d }|d u r$|jdd}t|tr8| }ntj|td}t	||| j
| j| j| j| j| j| j| j|d}|S )NT)Zboxedr  )	rT   rR   rP  r  rG   r   r   r8  rQ  )rO  r  
_formatterr{   r%   Z_internal_get_valuesr   r  r  r   rT   rR   rP  r  rG   r   r   r8  )re   rO  r  rQ  r  r   rf   rf   rg   rb    s,    

z(_ExtensionArrayFormatter._format_stringsNr   r   r   r  rb  rf   rf   rf   rg   r[    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 	|| }t |r|t
}dd |D S t | }t|}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   rj   z/percentiles should all be in the interval [0,1]d   c                 S  s   g | ]}|d  qS %rf   r   r   rf   rf   rg   r   >  r   z&format_percentiles.<locals>.<listcomp>r  c                 S  s   g | ]}|d  qS r  rf   r  rf   rf   rg   r   F  r   )r   r  r   r   r   get_precisionroundastyperm   iscloserZ   uniqueZ
empty_liker  )r  precZpercentiles_round_typeZint_idxoutZunique_pctsrf   rf   rg   format_percentiles
  s*    "



r  rm   )r  r_   c                 C  sx   | d dkr| d nd }| d dk r0d| d  nd }t j| ||d}t|}t t t |t }td|}|S )Nr   r  )to_beginto_endrj   )	r   Zediff1dr}  floorlog10rn   r  rm   r   )r  r  r  diffr  rf   rf   rg   r  I  s    
r  r   zNaTType | Timestamp)r   r  r_   c                 C  s   | t u r|S t| S r   )r   rZ   )r   r  rf   rf   rg   _format_datetime64S  s    r  )r   r  r<  r_   c                 C  s&   t | tr|S |r| |S | jS d S r   )r{   r   strftimeZ
_date_repr)r   r  r<  rf   rf   rg   _format_datetime64_dateonly\  s
    

r  rY   r   )is_dates_onlyr  r<  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  r<  )r  r  r<  r  rf   rg   rf  r  s   z'get_format_datetime64.<locals>.<lambda>c                   s   t |  dS )Nr  )r  r  r  rf   rg   rf  v  r   Nrf   )r  r  r<  rf   r  rg   get_format_datetime64k  s    r  c                   @  s$   e Zd ZU ded< ddddZdS )rY  r&   rO  r   ri   c                   s>   | j j}| j t}| jp&t|| jd  fdd|D }|S )zwe by definition have a TZ)r<  c                   s   g | ]} |qS rf   rf   r   r  rf   rg   r     r   z:_Datetime64TZFormatter._format_strings.<locals>.<listcomp>)rO  _is_dates_onlyr  r  r  r  r<  )re   ZidorO  r   rf   r  rg   rb  |  s    z&_Datetime64TZFormatter._format_stringsNr  rf   rf   rf   rg   rY  y  s   
rY  c                      s@   e Zd ZU ded< ddddd fddZd	d
ddZ  ZS )rZ  r(   rO  r   rZ   r]   )rO  r  r_   c                   s   t  j|fi | || _d S r   )rq  rh   r  )re   rO  r  rt  ru  rf   rg   rh     s    z_Timedelta64Formatter.__init__r   ri   c                   s,   | j pt| j| jdd  fdd| jD S )NF)r  boxc                   s   g | ]} |qS rf   rf   r   r  rf   rg   r     r   z9_Timedelta64Formatter._format_strings.<locals>.<listcomp>)r  get_format_timedelta64rO  r  r   rf   r  rg   rb    s    
z%_Timedelta64Formatter._format_strings)r   r  rf   rf   ru  rg   rZ    s   
 
rZ  Fr(   zstr | float)rO  r  r  r_   c                   s(   | j }|rd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
    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  rn  r  rf   rg   r    s    
z*get_format_timedelta64.<locals>._formatter)r  )rO  r  r  Z	even_daysr  rf   r  rg   r    s    r  zprinting._TextAdjustment | None)r   rG   r   rc   r_   c                   s   t | dks|dkr| S |d u r*t  n| t fdd| D |d urVt|tdd urrkrr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   )
adjustmentrf   rg   r     r   z$_make_fixed_width.<locals>.<genexpr>r   rZ   )r   r_   c                   s6   d ur2dk  | k@ r2| d d  d } | S )Nr   r   r  r  )r  conf_maxr  rf   rg   just  s    z_make_fixed_width.<locals>.justc                   s   g | ]} |qS rf   rf   r   )r  rf   rg   r     r   z%_make_fixed_width.<locals>.<listcomp>r   )rl   r4   rb   r   r   rG   )r   rG   r   rc   r   rf   )r  r  r  r  rg   r     s    

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+-])rt   Nr   c                 s  s   | ]}t |V  qd S r   r  )r   partrf   rf   rg   r     r   z&_trim_zeros_complex.<locals>.<genexpr>rj   c                   s6   g | ].\}}||d   |dd d   d qS )r   rj   N>r  rf   )r   Zreal_ptZimag_ptZpadded_lengthrf   rg   r     s   z'_trim_zeros_complex.<locals>.<listcomp>)rer   r   r   rl   r  r   r   )	r  r   Z	real_partZ	imag_partr   trimmednZpadded_partspaddedrf   r  rg   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  rf   rf   rg   rd    s    

rd  ArrayLike | 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]*$rY   ri   c                   s   t  | d uS r   )r  matchr  )number_regexrf   rg   is_number_with_decimal  s    z1_trim_zeros_float.<locals>.is_number_with_decimalr  )rO  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 rf   rf   r   r  rf   rg   r   #  r   z:_trim_zeros_float.<locals>.should_trim.<locals>.<listcomp>r   c                 s  s   | ]}| d V  qdS )r  Nr  r   rf   rf   rg   r   $  r   z9_trim_zeros_float.<locals>.should_trim.<locals>.<genexpr>)rl   r   )rO  numbersr  rf   rg   should_trim  s    z&_trim_zeros_float.<locals>.should_trimc                   s$   g | ]} |r|d d n|qS )Nr  rf   r   r  rf   rg   r   '  r   z%_trim_zeros_float.<locals>.<listcomp>c                   s*   g | ]"}|r"|  r"|d  n|qS )r  r  r   )r   r  rf   rg   r   *  s   )r  compile)r  r   r  r  r   rf   )r   r  r  rg   r    s    r  r+   )rQ   r_   c                 C  s$   t | trtj| j S | jd uS d S r   )r{   r,   comZany_not_noner  rS   )rQ   rf   rf   rg   r   1  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
    r  zarN  pr  urS  rt   r  rR  GTPEZY)iiiiiiir   r   r  	   rV              NFr\   rY   r]   accuracyuse_eng_prefixr_   c                 C  s   || _ || _d S r   r  r  )re   r  r  rf   rf   rg   rh   T  s    zEngFormatter.__init__floatrZ   )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
        rN   infrj   r   r  r   zE-02dzE+r  Nz{mant: g}{prefix}z{mant: .rc  z
f}{prefix})mantprefix)r	   rZ   is_nanis_infiniterm   mathr  r  rn   r   ENG_PREFIXESr   r  r  rn  )
re   r  ZdnumsignZpow10Z	int_pow10r  r  
format_strr  rf   rf   rg   __call__Z  s4    

 
zEngFormatter.__call__)NF)r   r   r   r   r  rh   r  rf   rf   rf   rg   r  8  s,    r  r   r]   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  rf   rf   rg   set_eng_float_format  s    7r  rt   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)rl   r   r   )	r  r  controlr   r
  Z
last_indexlengthsr   keyrf   rf   rg   get_level_lengths  s     r  zWriteBuffer[str])ra   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{   rZ   r   rf   rf   rg   r     r   z#buffer_put_lines.<locals>.<genexpr>c                 S  s   g | ]}t |qS rf   r  r   rf   rf   rg   r   	  r   z$buffer_put_lines.<locals>.<listcomp>rx   N)r  rH  r   )ra   r  rf   rf   rg   buffer_put_lines  s    r	  )NN)N)	NrN   NNrE   r   TNN)r   )r   N)r   N)r   F)rE   NN)r   )r   )r   F)rt   )r   
__future__r   collections.abcr   r   r   r   
contextlibr   csvr   r   r	   	functoolsr
   ior   r  r  shutilr   typingr   r   r   r   r   numpyr   Zpandas._config.configr   r   Zpandas._libsr   Zpandas._libs.missingr   Zpandas._libs.tslibsr   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'   r(   Zpandas.core.arrays.string_r)   Zpandas.core.baser*   Zpandas.core.commoncorecommonr  Zpandas.core.indexes.apir+   r,   r-   r.   Zpandas.core.indexes.datetimesr/   Zpandas.core.indexes.timedeltasr0   Zpandas.core.reshape.concatr1   Zpandas.io.commonr2   r3   r   r4   Zpandas._typingr5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   ZpandasrA   rB   rC   r  ZVALID_JUSTIFY_PARAMETERSrL   rM   r   r   r   r   r+  rG  r   r^  r\  r]  rX  r[  r  r  r  r  r  rY  rZ  r  r   r  rd  r  r   r  r  r  r	  rf   rf   rf   rg   <module>   s    88	 #!   H     (         &Un J!?
     $   "! $`; +