HOME


sh-3ll 1.0
DIR:/usr/local/lib64/python3.6/site-packages/pandas/io/formats/__pycache__/
Upload File :
Current File : //usr/local/lib64/python3.6/site-packages/pandas/io/formats/__pycache__/style.cpython-36.pyc
3

���h���@s�dZddlmZddlmZddlZddlmZddlm	Z	ddl
mZmZm
Z
mZmZmZmZmZmZddlmZddlZdd	lmZdd
lmZddlmZmZmZm Z ddl!m"Z"dd
l#m$Z$ddl%m&Z&ddl'Z(ddl)m*Z*m+Z+ddl,j-j.Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5m6Z6e"ddd�Z7yddl8m9Z9ddl:j;Z<dZ=Wne>k
�rddZ=dZ?YnXeed�dd��Z@Gdd�d�ZAeBd�d d!�ZCd'd"d#�ZDeeeEfeeEed$�d%d&�ZFdS)(zF
Module for applying conditional formatting to DataFrames and Series.
�)�defaultdict)�contextmanagerN)�partial)�product)	�Any�Callable�DefaultDict�Dict�List�Optional�Sequence�Tuple�Union)�uuid1)�
get_option)�lib)�Axis�
FrameOrSeries�FrameOrSeriesUnion�Label)�import_optional_dependency)�doc)�is_float)�is_dict_like�is_list_like)�	DataFrame)�NDFrame)�_maybe_numeric_slice�_non_reducing_slice�jinja2z DataFrame.style requires jinja2.)�extra)�colorsTFz{0} requires matplotlib.)�funcccs$trttfVnttj|j���dS)N)�has_mpl�pltr!�ImportError�no_mpl_message�format�__name__)r"�r)�9/tmp/pip-build-5_djhm0z/pandas/pandas/io/formats/style.py�_mpl6sr+c@seZdZdZejdd�Zejedd�Zej	d�Z
d~eee
eeeeeeeeffeeeeeeeeed�d	d
�Zed�dd
�Zeejdd�deeeeeeeeeeefeeeeeefe
e
eeeeeeeeee
e
fdd�dd��Zdd�Zd�eedd�dd�Zed�dd�Zedd�dd�Zd�edd!�d"d#�Z dd�d$d%�Z!dd�d&d'�Z"dd�d(d)�Z#d*d+�Z$d�e%d�ee&dd-�d.d/�Z'd�e%d�ee&dd-�d0d1�Z(d�e%dd2�d3d4�Z)d�e%dd2�d5d6�Z*d�e%eeedd7�d8d9�Z+e
dd:�d;d<�Z,edd=�d>d?�Z-eee%eefd�d@dA�Z.eee%eefddB�dCdD�Z/eddE�dFdG�Z0eddH�dIdJ�Z1dd�dKdL�Z2edd�dMdN�Z3dd�dOdP�Z4dd�dQdR�Z5e6eedS�dTdU��Z7d�eeeeeefddW�dXdY�Z8d�e9e9ee&e9ee9ee9dd\�d]d^�Z:e6d�e9e9e9ee9ee9d_�d`da��Z;d�dd�dbdc�Z<e6d�eeee9ee9ee9de�dfdg��Z=d�ee&e9eee9ee9ddj�dkdl�Z>d�eee&ddn�dodp�Z?d�eee&ddn�dqdr�Z@d�eee&edds�dtdu�ZAe6d�eBeedv�dwdx��ZCeDdydz��ZEe%d{�d|d}�ZFdS)��Stylera�	
    Helps style a DataFrame or Series according to the data with HTML and CSS.

    Parameters
    ----------
    data : Series or DataFrame
        Data to be styled - either a Series or DataFrame.
    precision : int
        Precision to round floats to, defaults to pd.options.display.precision.
    table_styles : list-like, default None
        List of {selector: (attr, value)} dicts; see Notes.
    uuid : str, default None
        A unique identifier to avoid CSS collisions; generated automatically.
    caption : str, default None
        Caption to attach to the table.
    table_attributes : str, default None
        Items that show up in the opening ``<table>`` tag
        in addition to automatic (by default) id.
    cell_ids : bool, default True
        If True, each cell will have an ``id`` attribute in their HTML tag.
        The ``id`` takes the form ``T_<uuid>_row<num_row>_col<num_col>``
        where ``<uuid>`` is the unique identifier, ``<num_row>`` is the row
        number and ``<num_col>`` is the column number.
    na_rep : str, optional
        Representation for missing values.
        If ``na_rep`` is None, no special formatting is applied.

        .. versionadded:: 1.0.0

    Attributes
    ----------
    env : Jinja2 jinja2.Environment
    template : Jinja2 Template
    loader : Jinja2 Loader

    See Also
    --------
    DataFrame.style : Return a Styler object containing methods for building
        a styled HTML representation for the DataFrame.

    Notes
    -----
    Most styling will be done by passing style functions into
    ``Styler.apply`` or ``Styler.applymap``. Style functions should
    return values with strings containing CSS ``'attr: value'`` that will
    be applied to the indicated cells.

    If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
    to automatically render itself. Otherwise call Styler.render to get
    the generated HTML.

    CSS classes are attached to the generated HTML

    * Index and Column names include ``index_name`` and ``level<k>``
      where `k` is its level in a MultiIndex
    * Index label cells include

      * ``row_heading``
      * ``row<n>`` where `n` is the numeric position of the row
      * ``level<k>`` where `k` is the level in a MultiIndex

    * Column label cells include
      * ``col_heading``
      * ``col<n>`` where `n` is the numeric position of the column
      * ``level<k>`` where `k` is the level in a MultiIndex

    * Blank cells include ``blank``
    * Data cells include ``data``
    �pandaszio/formats/templatesT)�loaderZtrim_blockszhtml.tplN)�data�	precision�table_styles�uuid�caption�table_attributes�cell_ids�na_repc		s�tt��_g�_t|tjtjf�s*td��|j	dkr<|j
�}|jjsP|j
jrXtd��|�_|j�_|j
�_
|�_|�_|�_|dkr�td�}|�_|�_d�_g�_|�_|�_�fdd��t�fdd	���_dS)
Nz&``data`` must be a Series or DataFrame�z.style is not supported for non-unique indices.zdisplay.precisionFcs@�jdk	rtj|�r�jSt|�r8|d�j�d��}|S|SdS)N�.�f)r6�pd�isnarr0)�xZdisplay_format)�selfr)r*�default_display_func�sz-Styler.__init__.<locals>.default_display_funccs�S)Nr)r))r>r)r*�<lambda>�sz!Styler.__init__.<locals>.<lambda>)r�list�ctx�_todo�
isinstancer:ZSeriesr�	TypeError�ndimZto_frame�indexZ	is_unique�columns�
ValueErrorr/r2r1r3rr0r4�hidden_index�hidden_columnsr5r6�_display_funcs)	r=r/r0r1r2r3r4r5r6r))r>r=r*�__init__�s0

zStyler.__init__)�returncCs|j�S)zB
        Hooks into Jupyter notebook rich display system.
        )�render)r=r)r)r*�_repr_html_�szStyler._repr_html_)�klass�Sheet1�r�inf)�
sheet_namer6�float_formatrG�headerrF�index_label�startrow�startcol�engine�merge_cells�encoding�inf_rep�verbose�freeze_panesrMcCs@ddlm}||||||||||d�	}|j|||	|
||d�dS)Nr)�ExcelFormatter)r6�colsrVrUrFrWr[r])rTrXrYr_rZ)Zpandas.io.formats.excelr`�write)r=Zexcel_writerrTr6rUrGrVrFrWrXrYrZr[r\r]r^r_r`�	formatterr)r)r*�to_excel�s$zStyler.to_excelc-
Cs\|jpg}|j}|j}|j}|j}|j}|jp>tt��j	dd�}d}d}	d}
d}d}d}
d	d
�}t
|j�}t
|j|�}t
�}|jjj}|jjj}|jjj�}|jjj�}|dkr�dd
�|D�}|dkr�dd
�|D�}tt|��}tt�}g}�xHt|�D�]:}d|
|
|dj|g�d�g|d}|jjj|}|dk�r>|n|
d|��g}|dk�rZ|
n|}|jd||dj|�|d��|r�x�t||�D]�\}}|	d|��d|��g}|j|jdi�j|i�j|g��d||dj|�t|||�d�}|j||fd�}|dk�r|d|d��g|d<|j|��q�W|j|�q�W|jjj�r�tj|jjj��r�|�r�g} xTt|jjj�D]B\}}|
d|��g}|dk�r�dn|}| jd|dj|�d���qrW| jd|
dj|g�d�gt|d�t|��|j| �g}!�x�t|jj�D�]�\}}"g}x�t||�D]�\}}|d|��d|��g}#dt|||��oT|||dj|#dd��dj|#�d�}|j||fd�}$|$dk�r�|d|$d��g|d<|j|��q"W�x,t|jj�D�]\}}%|d|��d|��g}|j|jdi�j|i�j|g��|j||f}&|jj ||f}d|dj|�|&|�||kd �}'g}(|j!�s\||f|k�r�dj|dd��|'d!<xB|||fD]2})|)j"d"��r�|(jt#|)j$d"���n
|(jd*��q�W|j|'�|t#|(�jd|�d#|����q�W|!j|��qWd$d
�|j%�D�}*|j&}+t'd%�},|,�sD|+�p"d}+d&|+k�r<|+j	d&d'�}+n|+d(7}+t
||*|!|||||+d)�S)+z�
        Convert the DataFrame in `self.data` and the attrs from `_build_styles`
        into a dictionary of {head, body, uuid, cellstyle}.
        �-�_Zrow_headingZcol_headingZ
index_namer/ZblankrRcSs|d�d|d��S)N�key�=�valuer))�pairr)r)r*�format_attrsz&Styler._translate.<locals>.format_attrr7cSsg|]
}|g�qSr)r))�.0r<r)r)r*�
<listcomp>sz%Styler._translate.<locals>.<listcomp>cSsg|]
}|g�qSr)r))rlr<r)r)r*rms�th� )�typeri�
display_value�
is_visible�classN�level)rprirqrsrr�colZcol_headingsr�colspan)rgri�
attributes)rprirs�row)rprrrirq�idrs�rowspan�td)rprirsrqrrry�:Z_colcSsg|]\}}t|�|d��qS))�props�	selectors)r@)rlr}r~r)r)r*rm�szdisplay.html.use_mathjaxzclass="zclass="tex2jax_ignore z class="tex2jax_ignore")�head�	cellstyle�bodyr2r0r1r3r4)rRrR)(r1r3rAr0rIrJr2�strr�replace�_get_level_lengthsrFrG�dictr/�nlevels�tolistr@�zipr�range�join�names�append�	enumerate�extend�get�_is_visible�comZany_not_none�lenrKZilocr5�count�tuple�split�itemsr4r)-r=r1r3rAr0rIrJr2ZROW_HEADING_CLASSZCOL_HEADING_CLASSZINDEX_NAME_CLASSZ
DATA_CLASSZBLANK_CLASSZBLANK_VALUErkZidx_lengthsZcol_lengthsZcell_contextZn_rlvlsZn_clvlsZrlabelsZclabelsZ
cellstyle_mapr�rZrow_es�name�cs�cri�esrvZindex_header_rowr��idxZridrzrurcZrow_dictr}r<r�Z
table_attrZuse_mathjaxr)r)r*�
_translate�s







"
$

zStyler._translate)r6rMcCs,|dkr"|jjdk	st�|jj�}|dkrJtt|j��}tt|jj��}nLt|�}t|�dkrj||jjf}|jj|}|jj	j
|j	�}|jjj
|j�}t|�r�x�|j�D]B\}}t
||�}|jjj
|g�d}	x|D]}
||j|
|	f<q�Wq�Wn8t
||�}t||f�}x |D]\}}
||j||
f<�qW|S)a�
        Format the text display value of cells.

        Parameters
        ----------
        formatter : str, callable, dict or None
            If ``formatter`` is None, the default formatter is used.
        subset : IndexSlice
            An argument to ``DataFrame.loc`` that restricts which elements
            ``formatter`` is applied to.
        na_rep : str, optional
            Representation for missing values.
            If ``na_rep`` is None, no special formatting is applied.

            .. versionadded:: 1.0.0

        Returns
        -------
        self : Styler

        Notes
        -----
        ``formatter`` is either an ``a`` or a dict ``{column name: a}`` where
        ``a`` is one of

        - str: this will be wrapped in: ``a.format(x)``
        - callable: called with the value of an individual cell

        The default display value for numeric values is the "general" (``g``)
        format with ``pd.options.display.precision`` precision.

        Examples
        --------
        >>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])
        >>> df.style.format("{:.2%}")
        >>> df['c'] = ['a', 'b', 'c', 'd']
        >>> df.style.format({'c': str.upper})
        Nr7r)rK�default_factory�AssertionErrorr�r�r/rGr�locrF�get_indexer_forrr��_maybe_wrap_formatterr)r=rc�subsetr6Zrow_locsZcol_locsZsub_dfruZ
col_formatterZcol_numZrow_numZlocs�i�jr)r)r*r'�s.'



z
Styler.formatcKsB|j�|j�}dd�|dD�}||d<|j|�|jjf|�S)a3
        Render the built up styles to HTML.

        Parameters
        ----------
        **kwargs
            Any additional keyword arguments are passed
            through to ``self.template.render``.
            This is useful when you need to provide
            additional variables for a custom template.

        Returns
        -------
        rendered : str
            The rendered HTML.

        Notes
        -----
        ``Styler`` objects have defined the ``_repr_html_`` method
        which automatically calls ``self.render()`` when it's the
        last item in a Notebook cell. When calling ``Styler.render()``
        directly, wrap the result in ``IPython.display.HTML`` to view
        the rendered HTML in the notebook.

        Pandas uses the following keys in render. Arguments passed
        in ``**kwargs`` take precedence, so think carefully if you want
        to override them:

        * head
        * cellstyle
        * body
        * uuid
        * precision
        * table_styles
        * caption
        * table_attributes
        cSs&g|]}tdd�|dD��r|�qS)css|]}t|�VqdS)N)�any)rl�yr)r)r*�	<genexpr>"sz+Styler.render.<locals>.<listcomp>.<genexpr>r})r�)rlr<r)r)r*rm"sz!Styler.render.<locals>.<listcomp>r�)�_computer��update�templaterN)r=�kwargs�dZtrimmedr)r)r*rN�s&
z
Styler.render)�attrsrMcCs�dd�t|j�D�}dd�t|j�D�}x�tt|j��D]x}|j|}||}x`||gj�D]N\}}|slq^|jd�}|s|q^||}	x&|jd�D]}
|j|	|fj	|
�q�Wq^Wq8WdS)af
        Update the state of the Styler.

        Collects a mapping of {index_label: ['<property>: <value>']}.

        Parameters
        ----------
        attrs : DataFrame
            should contain strings of '<property>: <value>;<prop2>: <val2>'
            Whitespace shouldn't matter and the final trailing ';' shouldn't
            matter.
        cSsi|]\}}||�qSr)r))rlr��kr)r)r*�
<dictcomp>4sz&Styler._update_ctx.<locals>.<dictcomp>cSsi|]\}}||�qSr)r))rlr�r�r)r)r*r�5s�;N)
r�rGrFr�r�Z
itertuples�rstripr�rAr�)r=r�ZcoliZrowiZjjZcnr�Zrnr�r�rjr)r)r*�_update_ctx's


zStyler._update_ctxF)�deepcopyrMcCsVt|j|j|j|j|j|jd�}|rBtj|j	�|_	tj|j
�|_
n|j	|_	|j
|_
|S)N)r0r3r2r1r6)r,r/r0r3r2r1r6�copyr�rArB)r=r�Zstylerr)r)r*�_copyCs
zStyler._copycCs|jdd�S)z'
        Deep copy by default.
        F)r�)r�)r=r)r)r*�__copy__TszStyler.__copy__cCs|jdd�S)NT)r�)r�)r=�memor)r)r*�__deepcopy__ZszStyler.__deepcopy__cCs|jj�g|_dS)zb
        Reset the styler, removing any previously applied styles.

        Returns None.
        N)rA�clearrB)r=r)r)r*r�]s
zStyler.clearcCs,|}x"|jD]\}}}||�||�}qW|S)a
        Execute the style functions built up in `self._todo`.

        Relies on the conventions that all style functions go through
        .apply or .applymap. The append styles to apply as tuples of

        (application method, *args, **kwargs)
        )rB)r=r�r"�argsr�r)r)r*r�fs	zStyler._compute.)r"�axisrMc	Ks�|dkrtd�n|}t|�}|jj|}|dk	rR|j|f|dd�|��}|j|_n\||f|�}t|tj�s~t	dt
|��d���|jj|j�o�|jj|j�s�t
dt
|��d���|j}|jj|j}||kr�t
dt
|��d|j�d|����|j|�|S)	N�expand)r�Zresult_typez	Function zE must return a DataFrame when passed to `Styler.apply` with axis=Nonez
Result of z3 must have identical index and columns as the inputz- returned the wrong shape.
Result has shape: z
Expected shape:   )�slicerr/r��applyrGrCr:rrD�reprrF�equalsrH�shaper�)	r=r"r�r�r�r/�resultZresult_shapeZexpected_shaper)r)r*�_applyts(

z
Styler._applycKs |jjdd�|||f|f�|S)at
        Apply a function column-wise, row-wise, or table-wise.

        Updates the HTML representation with the result.

        Parameters
        ----------
        func : function
            ``func`` should take a Series or DataFrame (depending
            on ``axis``), and return an object with the same shape.
            Must return a DataFrame with identical index and
            column labels when ``axis=None``.
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            Apply to each column (``axis=0`` or ``'index'``), to each row
            (``axis=1`` or ``'columns'``), or to the entire DataFrame at once
            with ``axis=None``.
        subset : IndexSlice
            A valid indexer to limit ``data`` to *before* applying the
            function. Consider using a pandas.IndexSlice.
        **kwargs : dict
            Pass along to ``func``.

        Returns
        -------
        self : Styler

        Notes
        -----
        The output shape of ``func`` should match the input, i.e. if
        ``x`` is the input row, column, or table (depending on ``axis``),
        then ``func(x).shape == x.shape`` should be true.

        This is similar to ``DataFrame.apply``, except that ``axis=None``
        applies the function to the entire DataFrame at once,
        rather than column-wise or row-wise.

        Examples
        --------
        >>> def highlight_max(x):
        ...     return ['background-color: yellow' if v == x.max() else ''
                        for v in x]
        ...
        >>> df = pd.DataFrame(np.random.randn(5, 2))
        >>> df.style.apply(highlight_max)
        cSs
t|d�S)Nr�)�getattr)�instancer)r)r*r?�szStyler.apply.<locals>.<lambda>)rBr�)r=r"r�r�r�r)r)r*r��s4zStyler.apply)r"rMcKsJt|f|�}|dkr"tjdd�}t|�}|jj|j|�}|j|�|S)N)rr:Z
IndexSlicerr/r��applymapr�)r=r"r�r�r�r)r)r*�	_applymap�s
zStyler._applymapcKs|jjdd�||f|f�|S)a/
        Apply a function elementwise.

        Updates the HTML representation with the result.

        Parameters
        ----------
        func : function
            ``func`` should take a scalar and return a scalar.
        subset : IndexSlice
            A valid indexer to limit ``data`` to *before* applying the
            function. Consider using a pandas.IndexSlice.
        **kwargs : dict
            Pass along to ``func``.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.where
        cSs
t|d�S)Nr�)r�)r�r)r)r*r?�sz!Styler.applymap.<locals>.<lambda>)rBr�)r=r"r�r�r)r)r*r��szStyler.applymap)�condri�otherrMcs.�dkrd�|j���fdd�fd|i|��S)a
        Apply a function elementwise.

        Updates the HTML representation with a style which is
        selected in accordance with the return value of a function.

        Parameters
        ----------
        cond : callable
            ``cond`` should take a scalar and return a boolean.
        value : str
            Applied when ``cond`` returns true.
        other : str
            Applied when ``cond`` returns false.
        subset : IndexSlice
            A valid indexer to limit ``data`` to *before* applying the
            function. Consider using a pandas.IndexSlice.
        **kwargs : dict
            Pass along to ``cond``.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.applymap
        NrRcs�|�r�S�S)Nr))�val)r�r�rir)r*r?"szStyler.where.<locals>.<lambda>r�)r�)r=r�rir�r�r�r))r�r�rir*�where�s$zStyler.where)r0rMcCs
||_|S)z�
        Set the precision used to render.

        Parameters
        ----------
        precision : int

        Returns
        -------
        self : Styler
        )r0)r=r0r)r)r*�
set_precision%szStyler.set_precision)rwrMcCs
||_|S)a�
        Set the table attributes.

        These are the items that show up in the opening ``<table>`` tag
        in addition to to automatic (by default) id.

        Parameters
        ----------
        attributes : str

        Returns
        -------
        self : Styler

        Examples
        --------
        >>> df = pd.DataFrame(np.random.randn(10, 4))
        >>> df.style.set_table_attributes('class="pure-table"')
        # ... <table class="pure-table"> ...
        )r4)r=rwr)r)r*�set_table_attributes4szStyler.set_table_attributescCs|jS)z�
        Export the styles to applied to the current Styler.

        Can be applied to a second style with ``Styler.use``.

        Returns
        -------
        styles : list

        See Also
        --------
        Styler.use
        )rB)r=r)r)r*�exportLsz
Styler.export)�stylesrMcCs|jj|�|S)a?
        Set the styles on the current Styler.

        Possibly uses styles from ``Styler.export``.

        Parameters
        ----------
        styles : list
            List of style functions.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.export
        )rBr�)r=r�r)r)r*�use\sz
Styler.use)r2rMcCs
||_|S)z�
        Set the uuid for a Styler.

        Parameters
        ----------
        uuid : str

        Returns
        -------
        self : Styler
        )r2)r=r2r)r)r*�set_uuidrszStyler.set_uuid)r3rMcCs
||_|S)z�
        Set the caption on a Styler.

        Parameters
        ----------
        caption : str

        Returns
        -------
        self : Styler
        )r3)r=r3r)r)r*�set_caption�szStyler.set_captioncCs
||_|S)aC
        Set the table styles on a Styler.

        These are placed in a ``<style>`` tag before the generated HTML table.

        Parameters
        ----------
        table_styles : list
            Each individual table_style should be a dictionary with
            ``selector`` and ``props`` keys. ``selector`` should be a CSS
            selector that the style will be applied to (automatically
            prefixed by the table's UUID) and ``props`` should be a list of
            tuples with ``(attribute, value)``.

        Returns
        -------
        self : Styler

        Examples
        --------
        >>> df = pd.DataFrame(np.random.randn(10, 4))
        >>> df.style.set_table_styles(
        ...     [{'selector': 'tr:hover',
        ...       'props': [('background-color', 'yellow')]}]
        ... )
        )r1)r=r1r)r)r*�set_table_styles�szStyler.set_table_stylescCs
||_|S)z�
        Set the missing data representation on a Styler.

        .. versionadded:: 1.0.0

        Parameters
        ----------
        na_rep : str

        Returns
        -------
        self : Styler
        )r6)r=r6r)r)r*�
set_na_rep�szStyler.set_na_repcCs
d|_|S)z�
        Hide any indices from rendering.

        .. versionadded:: 0.23.0

        Returns
        -------
        self : Styler
        T)rI)r=r)r)r*�
hide_index�s
zStyler.hide_indexcCs(t|�}|jj|}|jj|j�|_|S)a-
        Hide columns from rendering.

        .. versionadded:: 0.23.0

        Parameters
        ----------
        subset : IndexSlice
            An argument to ``DataFrame.loc`` that identifies which columns
            are hidden.

        Returns
        -------
        self : Styler
        )rr/r�rGr�rJ)r=r�Z	hidden_dfr)r)r*�hide_columns�szStyler.hide_columns)�
null_colorrMcCstj|�rd|��SdS)Nzbackground-color: rR)r:r;)�vr�r)r)r*�_highlight_null�szStyler._highlight_null�red)r�r�rMcCs|j|j||d�|S)au
        Shade the background ``null_color`` for missing values.

        Parameters
        ----------
        null_color : str, default 'red'
        subset : label or list of labels, default None
            A valid slice for ``data`` to limit the style application to.

            .. versionadded:: 1.1.0

        Returns
        -------
        self : Styler
        )r�r�)r�r�)r=r�r�r)r)r*�highlight_null�szStyler.highlight_null�PuBu��&1��?)�low�highr��text_color_threshold�vmin�vmaxrMc		Cs6t|j|�}t|�}|j|j||||||||d�	|S)a�
        Color the background in a gradient style.

        The background color is determined according
        to the data in each column (optionally row). Requires matplotlib.

        Parameters
        ----------
        cmap : str or colormap
            Matplotlib colormap.
        low : float
            Compress the range by the low.
        high : float
            Compress the range by the high.
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            Apply to each column (``axis=0`` or ``'index'``), to each row
            (``axis=1`` or ``'columns'``), or to the entire DataFrame at once
            with ``axis=None``.
        subset : IndexSlice
            A valid slice for ``data`` to limit the style application to.
        text_color_threshold : float or int
            Luminance threshold for determining text color. Facilitates text
            visibility across varying background colors. From 0 to 1.
            0 = all text is dark colored, 1 = all text is light colored.

            .. versionadded:: 0.24.0

        vmin : float, optional
            Minimum data value that corresponds to colormap minimum value.
            When None (default): the minimum value of the data will be used.

            .. versionadded:: 1.0.0

        vmax : float, optional
            Maximum data value that corresponds to colormap maximum value.
            When None (default): the maximum value of the data will be used.

            .. versionadded:: 1.0.0

        Returns
        -------
        self : Styler

        Raises
        ------
        ValueError
            If ``text_color_threshold`` is not a value from 0 to 1.

        Notes
        -----
        Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the
        text legible by not using the entire range of the color map. The range
        of the data is extended by ``low * (x.max() - x.min())`` and ``high *
        (x.max() - x.min())`` before normalizing.
        )�cmapr�r�r�r�r�r�r�)rr/rr��_background_gradient)	r=r�r�r�r�r�r�r�r�r)r)r*�background_gradientsBzStyler.background_gradient)r�r�r�r�r�cs*t�ttf�s*d�ko"dknr6d}t|��ttj���\}�|dkr\tj|j	��n|}	|dkrvtj
|j	��n|}
|
|	}�j|	|||
||�}|jj
|�||j	td���}
td�dd��td����fd	d
��|jdkr��fdd�|
D�Stj�fd
d�|
D�|j|jd�SWdQRXdS)zD
        Color background in a range according to the data.
        rr7z3`text_color_threshold` must be a value from 0 to 1.N)�dtype)rMcSs4dd�|dd�D�\}}}d|d|d|S)a�
                Calculate relative luminance of a color.

                The calculation adheres to the W3C standards
                (https://www.w3.org/WAI/GL/wiki/Relative_luminance)

                Parameters
                ----------
                color : rgb or rgba tuple

                Returns
                -------
                float
                    The relative luminance as a value from 0 to 1
                css*|]"}|dkr|dn
|ddVqdS)g#���?gףp=
�)@g)\��(�?g�z�G��?g333333@Ng6��1�?r))rlr<r)r)r*r��szJStyler._background_gradient.<locals>.relative_luminance.<locals>.<genexpr>N�g���z6�?g�,C���?g]m��{�?r))�rgbar��g�br)r)r*�relative_luminanceosz7Styler._background_gradient.<locals>.relative_luminancecs0�|��k}|rdnd}d�j|��d|�d�S)Nz#f1f1f1z#000000zbackground-color: z;color: r�)Zrgb2hex)r�ZdarkZ
text_color)r!r�r�r)r*�css�sz(Styler._background_gradient.<locals>.csscsg|]}�|��qSr)r))rlr�)r�r)r*rm�sz/Styler._background_gradient.<locals>.<listcomp>csg|]}�fdd�|D��qS)csg|]}�|��qSr)r))rlr�)r�r)r*rm�sz:Styler._background_gradient.<locals>.<listcomp>.<listcomp>r))rlrx)r�r)r*rm�s)rFrG)rC�float�intrHr+r,r��np�nanmin�to_numpy�nanmaxZ	Normalize�cmZget_cmapr�rEr:rrFrG)�sr�r�r�r�r�r��msgr$�smin�smax�rngZnormZrgbasr))r!r�r�r�r*r�Qs$
zStyler._background_gradientcs2djdd�|j�D����fdd�}|j||d�S)a_
        Method to set one or more non-data dependent properties or each cell.

        Parameters
        ----------
        subset : IndexSlice
            A valid slice for ``data`` to limit the style application to.
        **kwargs : dict
            A dictionary of property, value pairs to be set for each cell.

        Returns
        -------
        self : Styler

        Examples
        --------
        >>> df = pd.DataFrame(np.random.randn(10, 4))
        >>> df.style.set_properties(color="white", align="right")
        >>> df.style.set_properties(**{'background-color': 'yellow'})
        r�css |]\}}|�d|��VqdS)z: Nr))rl�pr�r)r)r*r��sz(Styler.set_properties.<locals>.<genexpr>cs�S)Nr))r<)�valuesr)r*r?�sz'Styler.set_properties.<locals>.<lambda>)r�)r�r�r�)r=r�r�r9r))r�r*�set_properties�szStyler.set_properties�d)�alignr!�widthr�r�c	s|dkrtj|j��n|}|dkr0tj|j��n|}�dkrRtd|�}td|�}n �dkrrtt|�t|��}|}�|jtd�|||d}�|||d�ttttd��fdd	������fd
d��|j	dkr�fd
d�|D�St
j�fdd�|D�|j|j
d�SdS)z4
        Draw bar chart in dataframe cells.
        N�midr�zero)r�g�-���q=)�start�end�colorrMcshd}||krd|d7}|dkr<|d|d�d|�d|d�d�7}t|��}||�d|d�d|d�d	�7}|S)
zL
            Generate CSS code to draw a bar from start to end.
            zwidth: 10em; height: 80%;z"background: linear-gradient(90deg,rz
 transparent z.1fz%, roz%, transparent z%))�min)rrrr��e)r�r)r*�css_bar�s 
zStyler._bar.<locals>.css_barcsVtj|�rdS|�kr�dn�d}�dkr:�d||�S�t|��t|��|�SdS)NrRr7r�left)r:r;r�max)r<r)r�r!rrr)r*r��s
zStyler._bar.<locals>.cssr7csg|]}�|��qSr)r))rlr<)r�r)r*rm�szStyler._bar.<locals>.<listcomp>csg|]}�fdd�|D��qS)csg|]}�|��qSr)r))rlr<)r�r)r*rm�sz*Styler._bar.<locals>.<listcomp>.<listcomp>r))rlrx)r�r)r*rm�s)rFrG)r�r�r�r�rr	�absr�r�rEr:rrFrG)	r�r�r!r�r�r�r�r�Znormedr))r�r!r�rr�rr*�_bar�s$

 

zStyler._bar�#d65f5fr)r�r�r�r�r�rMc
Cs�|d
krtd��t|�s"||g}n2t|�dkr@|d|dg}nt|�dkrTtd��t|j|�}t|�}|j|j|||||||d	�|S)a�
        Draw bar chart in the cell backgrounds.

        Parameters
        ----------
        subset : IndexSlice, optional
            A valid slice for `data` to limit the style application to.
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            Apply to each column (``axis=0`` or ``'index'``), to each row
            (``axis=1`` or ``'columns'``), or to the entire DataFrame at once
            with ``axis=None``.
        color : str or 2-tuple/list
            If a str is passed, the color is the same for both
            negative and positive numbers. If 2-tuple/list is used, the
            first element is the color_negative and the second is the
            color_positive (eg: ['#d65f5f', '#5fba7d']).
        width : float, default 100
            A number between 0 or 100. The largest value will cover `width`
            percent of the cell's width.
        align : {'left', 'zero',' mid'}, default 'left'
            How to align the bars with the cells.

            - 'left' : the min value starts at the left of the cell.
            - 'zero' : a value of zero is located at the center of the cell.
            - 'mid' : the center of the cell is at (max-min)/2, or
              if values are all negative (positive) the zero is aligned
              at the right (left) of the cell.
        vmin : float, optional
            Minimum bar value, defining the left hand limit
            of the bar drawing range, lower values are clipped to `vmin`.
            When None (default): the minimum value of the data will be used.

            .. versionadded:: 0.24.0

        vmax : float, optional
            Maximum bar value, defining the right hand limit
            of the bar drawing range, higher values are clipped to `vmax`.
            When None (default): the maximum value of the data will be used.

            .. versionadded:: 0.24.0

        Returns
        -------
        self : Styler
        rrrz.`align` must be one of {'left', 'zero',' mid'}r7r�zp`color` must be string or a list-like of length 2: [`color_neg`, `color_pos`] (eg: color=['#d65f5f', '#5fba7d']))r�r�r�r!r�r�r�)rrr)rHrr�rr/rr�r)r=r�r�rr�r�r�r�r)r)r*�bar�s*7
z
Styler.bar�yellow)rr�rMcCs|j|||dd�S)a1
        Highlight the maximum by shading the background.

        Parameters
        ----------
        subset : IndexSlice, default None
            A valid slice for ``data`` to limit the style application to.
        color : str, default 'yellow'
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            Apply to each column (``axis=0`` or ``'index'``), to each row
            (``axis=1`` or ``'columns'``), or to the entire DataFrame at once
            with ``axis=None``.

        Returns
        -------
        self : Styler
        T)r�rr��max_)�_highlight_handler)r=r�rr�r)r)r*�
highlight_max<szStyler.highlight_maxcCs|j|||dd�S)a1
        Highlight the minimum by shading the background.

        Parameters
        ----------
        subset : IndexSlice, default None
            A valid slice for ``data`` to limit the style application to.
        color : str, default 'yellow'
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            Apply to each column (``axis=0`` or ``'index'``), to each row
            (``axis=1`` or ``'columns'``), or to the entire DataFrame at once
            with ``axis=None``.

        Returns
        -------
        self : Styler
        F)r�rr�r)r)r=r�rr�r)r)r*�
highlight_minRszStyler.highlight_min)rr�rrMcCs*tt|j|��}|j|j||||d�|S)N)rr�r�r)rrr/r��_highlight_extrema)r=r�rr�rr)r)r*rjszStyler._highlight_handler)r/rrcsrd|���|r"|tj|j��k}n|tj|j��k}|jdkrP�fdd�|D�Stjtj|�d�|j|j	d�SdS)zD
        Highlight the min or max in a Series or DataFrame.
        zbackground-color: r7csg|]}|r�nd�qS)rRr))rlr�)�attrr)r*rm�sz-Styler._highlight_extrema.<locals>.<listcomp>rR)rFrGN)
r�r�r�r�rEr:rr�rFrG)r/rrZextremar))rr*rws

zStyler._highlight_extremacs0tjtj|�|jg��G��fdd�d|�}|S)a�
        Factory function for creating a subclass of ``Styler``.

        Uses a custom template and Jinja environment.

        Parameters
        ----------
        searchpath : str or list
            Path or paths of directories containing the templates.
        name : str
            Name of your custom template to use for rendering.

        Returns
        -------
        MyStyler : subclass of Styler
            Has the correct ``env`` and ``template`` class attributes set.
        cs"eZdZej�d�Zej��ZdS)z-Styler.from_custom_template.<locals>.MyStyler)r.N)r(�
__module__�__qualname__r�Environment�env�get_templater�r))r.r�r)r*�MyStyler�sr)rZChoiceLoaderZFileSystemLoaderr.)�clsZ
searchpathr�rr))r.r�r*�from_custom_template�szStyler.from_custom_template)r"cOstj||f|�|�S)au	
        Apply ``func(self, *args, **kwargs)``, and return the result.

        .. versionadded:: 0.24.0

        Parameters
        ----------
        func : function
            Function to apply to the Styler.  Alternatively, a
            ``(callable, keyword)`` tuple where ``keyword`` is a string
            indicating the keyword of ``callable`` that expects the Styler.
        *args : optional
            Arguments passed to `func`.
        **kwargs : optional
            A dictionary of keyword arguments passed into ``func``.

        Returns
        -------
        object :
            The value returned by ``func``.

        See Also
        --------
        DataFrame.pipe : Analogous method for DataFrame.
        Styler.apply : Apply a function row-wise, column-wise, or table-wise to
            modify the dataframe's styling.

        Notes
        -----
        Like :meth:`DataFrame.pipe`, this method can simplify the
        application of several user-defined functions to a styler.  Instead
        of writing:

        .. code-block:: python

            f(g(df.style.set_precision(3), arg1=a), arg2=b, arg3=c)

        users can write:

        .. code-block:: python

            (df.style.set_precision(3)
               .pipe(g, arg1=a)
               .pipe(f, arg2=b, arg3=c))

        In particular, this allows users to define functions that take a
        styler object, along with other parameters, and return the styler after
        making styling changes (such as calling :meth:`Styler.apply` or
        :meth:`Styler.set_properties`).  Using ``.pipe``, these user-defined
        style "transformations" can be interleaved with calls to the built-in
        Styler interface.

        Examples
        --------
        >>> def format_conversion(styler):
        ...     return (styler.set_properties(**{'text-align': 'right'})
        ...                   .format({'conversion': '{:.1%}'}))

        The user-defined ``format_conversion`` function above can be called
        within a sequence of other style modifications:

        >>> df = pd.DataFrame({'trial': list(range(5)),
        ...                    'conversion': [0.75, 0.85, np.nan, 0.7, 0.72]})
        >>> (df.style
        ...    .highlight_min(subset=['conversion'], color='yellow')
        ...    .pipe(format_conversion)
        ...    .set_caption("Results with minimum conversion highlighted."))
        )r��pipe)r=r"r�r�r)r)r*r�sEzStyler.pipe)NNNNNTN)rQrRNNTTNrrNTNrSTN)NN)F)rN).r,)rN).r,)N)N)NN)r�N)r�rrrNr�NN)r�rrr�NN)N)r�NN)Nrrr�rNN)Nrr)Nrr)NrNT)rT)Gr(rr�__doc__rZ
PackageLoaderr.rrrr�rrr�r
r	r�r
�boolrLrOrrrdrrrr�r'rNrr�r�r�r�r�r�rrr�r�r�r�r�r�r�r�r�r�r�r�r�r�r��staticmethodr�r�r�r�r�r�rrrrrrr�classmethodrrr)r)r)r*r,>s�E
N+\BG1	$3	!$
G":&7L

r,)rMcCs||f|kS)z/
    Index -> {(idx_row, idx_col): bool}).
    r))Zidx_rowZidx_col�lengthsr)r)r*r��sr�cCs"t|tj�r|jtjdd�}n|j�}|dkr2g}i}|jdkrnx(t|�D]\}}||krJd|d|f<qJW|Sx�t|�D]�\}}x�t|�D]z\}}td�s�d|||f<q�|tjk	r�||kr�|}	d|||	f<q�|tjk	r�|}	d|||	f<q�||kr�|||	fd7<q�WqxWdd�|j	�D�}
|
S)	z�
    Given an index, find the level length for each element.

    Optional argument is a list of index positions which
    should not be visible.

    Result is a dictionary of (level, initial_position): span
    F)ZsparsifyZadjoinNr7rzdisplay.multi_sparsecSsi|]\}}|dkr||�qS)r7r))rl�element�lengthr)r)r*r�sz&_get_level_lengths.<locals>.<dictcomp>)
rCr:Z
MultiIndexr'rZ
no_defaultr�r�rr�)rFZhidden_elementsZlevelsr#r�riZlvlr�rxZ
last_labelZnon_zero_lengthsr)r)r*r��s4	

r�)rcr6rMcsvt�t�r�fdd��n"t��r&��nd��d�}t|���dkrF�St�t�r^��fdd�Sd��d�}t|��dS)Ncs
�j|�S)N)r')r<)rcr)r*r?(sz'_maybe_wrap_formatter.<locals>.<lambda>z,Expected a template string or callable, got z insteadcstj|�r�S�|�S)N)r:r;)r<)�formatter_funcr6r)r*r?2szExpected a string, got )rCr��callablerD)rcr6r�r))rcr&r6r*r�$s

r�)N)Gr�collectionsr�
contextlibrr��	functoolsr�	itertoolsrZtypingrrrr	r
rrr
rr2rZnumpyr�Zpandas._configrZpandas._libsrZpandas._typingrrrrZpandas.compat._optionalrZpandas.util._decoratorsrZpandas.core.dtypes.commonrr-r:Zpandas.api.typesrrZpandas.core.common�core�commonr�Zpandas.core.framerZpandas.core.genericrZpandas.core.indexingrrrZ
matplotlibr!Zmatplotlib.pyplotZpyplotr$r#r%r&r+r,r r�r�r�r�r)r)r)r*�<module>s\,

<
/