3
Êb_5À  ã               @   s€  d Z ddlmZ ddlmZ ddlZddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZmZmZ ddlmZ ddl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#m$Z$m%Z% ddl&j'j(Z)ddl*m+Z+ ddl,m-Z-m.Z. eddd�Z/yddl0j1Z2ddl3m4Z4 dZ5W n e6k
�r<   dZ5dZ7Y nX edd„ ƒZ8G dd„ dƒZ9dd„ Z:d#dd„Z;ee< d œd!d"„Z=dS )$zF
Module for applying conditional formatting to
DataFrames and Series.
é    )Údefaultdict)ÚcontextmanagerN)Úpartial)Úproduct)ÚAnyÚCallableÚDefaultDictÚDictÚListÚOptionalÚSequenceÚTuple)Úuuid1)Ú
get_option)Úlib)Úimport_optional_dependency)ÚAppender)Úis_float)Úis_dict_likeÚis_list_like)Ú_shared_docs)Ú_maybe_numeric_sliceÚ_non_reducing_sliceÚjinja2z DataFrame.style requires jinja2.)Úextra)ÚcolorsTFz{0} requires matplotlib.c             c   s$   t rttfV  nttj| jƒƒ‚d S )N)Úhas_mplÚpltr   ÚImportErrorÚno_mpl_messageÚformatÚ__name__)Úfunc© r#   ú9/tmp/pip-build-jkwsxyiy/pandas/pandas/io/formats/style.pyÚ_mpl+   s    r%   c               @   s  e Zd ZdZejddƒZejedd�Zej	dƒZ
dmee dœd	d
„Zdd„ Zeed edd dddd� ƒdndd„ƒZdd„ Zdoee dœdd„Zdd„ Zdd „ Zdpd"d#„Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zdqd,d-„Zdrd.d/„Zdsd0d1„Zdtd2d3„Zdud4d5„Z d6d7„ Z!d8d9„ Z"d:d;„ Z#d<d=„ Z$d>d?„ Z%d@dA„ Z&dBdC„ Z'ed dDœdEdF„Z(dGdH„ Z)dIdJ„ Z*e+dKdL„ ƒZ,dvdNdO„Z-dwee. ee. dRœdSdT„Z/e+dxee. ee. dRœdUdV„ƒZ0dydWdX„Z1e+dzdZd[„ƒZ2d{d^d_„Z3d|dadb„Z4d}dcdd„Z5d~dedf„Z6e+ddgdh„ƒZ7e8didj„ ƒZ9dkdl„ Z:dS )€Ú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
      * ``evel<k>`` where `k` is the level in a MultiIndex

    * Blank cells include ``blank``
    * Data cells include ``data``
    Úpandaszio/formats/templatesT)ÚloaderZtrim_blockszhtml.tplN)Úna_repc	       	         sÖ   t tƒˆ_g ˆ_t|tjtjfƒs*tdƒ‚|j	dkr<|j
ƒ }|jj sP|jj rXtdƒ‚|ˆ_|jˆ_|jˆ_|ˆ_|ˆ_|ˆ_|d kr�tdƒ}|ˆ_|ˆ_dˆ_g ˆ_|ˆ_|ˆ_‡fdd„‰ t ‡ fdd	„ƒˆ_d S )
Nz&``data`` must be a Series or DataFrameé   z.style is not supported for non-unique indices.zdisplay.precisionFc                s@   ˆ j d k	rtj| ƒrˆ j S t| ƒr8| dˆ j› d�›}|S | S d S )NÚ.Úf)r)   ÚpdÚisnar   Ú	precision)ÚxZdisplay_format)Úselfr#   r$   Údefault_display_func¥   s    z-Styler.__init__.<locals>.default_display_funcc                  s   ˆ S )Nr#   r#   )r2   r#   r$   Ú<lambda>°   s    z!Styler.__init__.<locals>.<lambda>)r   ÚlistÚctxÚ_todoÚ
isinstancer-   ZSeriesÚ	DataFrameÚ	TypeErrorÚndimZto_frameÚindexZ	is_uniqueÚcolumnsÚ
ValueErrorÚdataÚuuidÚtable_stylesÚcaptionr   r/   Útable_attributesÚhidden_indexÚhidden_columnsÚcell_idsr)   Ú_display_funcs)	r1   r>   r/   r@   r?   rA   rB   rE   r)   r#   )r2   r1   r$   Ú__init__~   s0    

zStyler.__init__c             C   s   | j ƒ S )zB
        Hooks into Jupyter notebook rich display system.
        )Úrender)r1   r#   r#   r$   Ú_repr_html_²   s    zStyler._repr_html_Úto_excelzindex, columnsz{0 or 'index', 1 or 'columns'}zi
            by : str or list of str
                Name or list of names which refer to the axis items.z
    .. versionadded:: 0.20)ZaxesÚklassZaxes_single_argZoptional_byZversionadded_to_excelÚSheet1Ú r   Úinfc             C   s@   ddl m} || ||||||||d�	}|j|||	|
||d� d S )Nr   )ÚExcelFormatter)r)   ÚcolsÚheaderÚfloat_formatr;   Úindex_labelÚmerge_cellsÚinf_rep)Ú
sheet_nameÚstartrowÚstartcolÚfreeze_panesÚengine)Zpandas.io.formats.excelrO   Úwrite)r1   Zexcel_writerrV   r)   rR   r<   rQ   r;   rS   rW   rX   rZ   rT   ÚencodingrU   ÚverboserY   rO   Ú	formatterr#   r#   r$   rJ   ¸   s$     zStyler.to_excelc       ,   
   C   sd  | j pg }| j}| j}| j}| j}| j}| jp>ttƒ ƒj	ddƒ}d}d}	d}
d}d}d}d	d
„ }t
| jƒ}t
| j|ƒ}tƒ }| jjj}| jjj}| jjjƒ }| jjjƒ }|dkr¾dd„ |D ƒ}|dkrÔdd„ |D ƒ}tt|Ž ƒ}g }g }�xHt|ƒD �]:}d||| dj|gƒdœg|d  }| jjj| }|dk�r:|n|
d|› �g}|dk�rV|n|}|jd||dj|ƒ| dœƒ |rôx¨t|| ƒD ]˜\}}|	d|› �d|› �g}|j|jdi ƒj|i ƒj|g ƒƒ d||dj|ƒt|||ƒdœ}|j||fdƒ}|dk�r|d|dœƒg|d< |j|ƒ �qŠW |j|ƒ qôW | jjj�rîtj| jjjŽ �rî| �rîg } xTt| jjjƒD ]B\}}|
d|› �g}|dk�r’dn|}| jd|dj|ƒdœƒ �qnW | jd|dj|gƒdœgt|d ƒt|ƒ  ƒ |j| ƒ g }!�xt| jjƒD �]\}}"g }xžt|| ƒD ]Ž\}}|d|› �d|› �g}#dt|||ƒ�oP| ||dj|#dd… ƒdj|#ƒdœ}|j||fdƒ}$|$dk�r |d|$dœƒg|d< |j|ƒ �qW �xJt| jjƒD �]8\}}%|d|› �d|› �g}|j|jdi ƒj|i ƒj|g ƒƒ | j||f }&| jj||f }d|dj|ƒ|&|ƒ||kd œ}'| j �stt|||f ƒdk�on|||f d dk �rŠdj|dd… ƒ|'d!< |j|'ƒ g }(xB|||f D ]2})|)j!d"ƒ�rÈ|(j|)j"d"ƒƒ n|(jddgƒ �q¦W |j|(d|› d#|› �d$œƒ �qÀW |!j|ƒ �qW | j#}*t$d%ƒ}+|+�sL|*�p*d}*d&|*k�rD|*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}.
        ú-Ú_Zrow_headingZcol_headingZ
index_namer>   ZblankrM   c             S   s   | d › d| d › �S )NÚkeyú=Úvaluer#   )Úpairr#   r#   r$   Úformat_attr  s    z&Styler._translate.<locals>.format_attrr*   c             S   s   g | ]
}|g‘qS r#   r#   )Ú.0r0   r#   r#   r$   ú
<listcomp>  s    z%Styler._translate.<locals>.<listcomp>c             S   s   g | ]
}|g‘qS r#   r#   )rf   r0   r#   r#   r$   rg     s    Úthú )Útyperc   Údisplay_valueÚ
is_visibleÚclassNÚlevel)rj   rc   rk   rm   rl   ÚcolZcol_headingsr   Úcolspan)ra   rc   Ú
attributes)rj   rc   rm   Úrow)rj   rl   rc   rk   Úidrm   ÚrowspanÚtd)rj   rc   rm   rk   rl   rs   ú:Z_col)ÚpropsÚselectorzdisplay.html.use_mathjaxzclass="zclass="tex2jax_ignore z class="tex2jax_ignore")ÚheadÚ	cellstyleÚbodyr?   r/   r@   rA   rB   )%r@   rA   r5   r/   rC   rD   r?   Ústrr   ÚreplaceÚ_get_level_lengthsr;   r<   Údictr>   ÚnlevelsÚtolistr4   ÚzipÚrangeÚjoinÚnamesÚappendÚ	enumerateÚextendÚgetÚ_is_visibleÚcomZany_not_noneÚlenrF   ZilocrE   ÚcountÚsplitrB   r   ),r1   r@   rA   r5   r/   rC   rD   r?   ZROW_HEADING_CLASSZCOL_HEADING_CLASSZINDEX_NAME_CLASSZ
DATA_CLASSZBLANK_CLASSZBLANK_VALUEre   Zidx_lengthsZcol_lengthsZcell_contextZn_rlvlsZn_clvlsZrlabelsZclabelsrz   ry   ÚrZrow_esÚnameÚcsÚcrc   Úesrp   Zindex_header_rowr{   ÚidxZridrt   ro   r^   Zrow_dictrw   r0   Z
table_attrZuse_mathjaxr#   r#   r$   Ú
_translateî   s    







"6
"

zStyler._translatec             C   s,  |dkr"| j jdk	st‚| j jƒ }|dkrJtt| jƒƒ}tt| jjƒƒ}nLt|ƒ}t|ƒdkrj|| jjf}| jj| }| jj	j
|j	ƒ}| jjj
|jƒ}t|ƒrðxˆ|jƒ D ]B\}}t||ƒ}| jjj
|gƒd }	x|D ]}
|| j |
|	f< qÔW q¨W n8t||ƒ}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})
        Nr*   r   )rF   Údefault_factoryÚAssertionErrorrƒ   rŒ   r>   r<   r   Úlocr;   Úget_indexer_forr   ÚitemsÚ_maybe_wrap_formatterr   )r1   r^   Úsubsetr)   Zrow_locsZcol_locsZsub_dfro   Zcol_formatterZcol_numZrow_numZlocsÚiÚjr#   r#   r$   r    ª  s.    )



zStyler.formatc             K   sB   | j ƒ  | jƒ }dd„ |d D ƒ}||d< |j|ƒ | jjf |Ž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
        c             S   s&   g | ]}t d d„ |d D ƒƒr|‘qS )c             s   s   | ]}t |ƒV  qd S )N)Úany)rf   Úyr#   r#   r$   ú	<genexpr>  s    z+Styler.render.<locals>.<listcomp>.<genexpr>rw   )rŸ   )rf   r0   r#   r#   r$   rg     s    z!Styler.render.<locals>.<listcomp>rz   )Ú_computer•   ÚupdateÚtemplaterH   )r1   ÚkwargsÚdZtrimmedr#   r#   r$   rH   ó  s    &
zStyler.renderc       	      C   s‚   x||j ƒ D ]p\}}xf|jƒ D ]Z\}}| jj|gƒd }| jj|gƒd }x,|jdƒjdƒD ]}| j||f j|ƒ qZW qW q
W dS )a>  
        Update the state of the Styler.

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

        attrs : Series or DataFrame
        should contain strings of '<property>: <value>;<prop2>: <val2>'
        Whitespace shouldn't matter and the final trailing ';' shouldn't
        matter.
        r   ú;N)	Ziterrowsrš   r;   Zget_indexerr<   ÚrstriprŽ   r5   r†   )	r1   ÚattrsZ	row_labelÚvZ	col_labelro   r�   rž   rd   r#   r#   r$   Ú_update_ctx$  s    zStyler._update_ctxFc             C   sV   t | j| j| j| j| j| jd�}|rBtj| j	ƒ|_	tj| j
ƒ|_
n| j	|_	| j
|_
|S )N)r/   rA   r?   r@   r)   )r&   r>   r/   rA   r?   r@   r)   ÚcopyÚdeepcopyr5   r6   )r1   r­   Zstylerr#   r#   r$   Ú_copy6  s    
zStyler._copyc             C   s   | j dd�S )z'
        Deep copy by default.
        F)r­   )r®   )r1   r#   r#   r$   Ú__copy__G  s    zStyler.__copy__c             C   s   | j dd�S )NT)r­   )r®   )r1   Úmemor#   r#   r$   Ú__deepcopy__M  s    zStyler.__deepcopy__c             C   s   | j jƒ  g | _dS )zb
        Reset the styler, removing any previously applied styles.

        Returns None.
        N)r5   Úclearr6   )r1   r#   r#   r$   r²   P  s    
zStyler.clearc             C   s,   | }x"| j D ]\}}}|| ƒ||Ž}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)
        )r6   )r1   r�   r"   Úargsr¥   r#   r#   r$   r¢   Y  s    	zStyler._computec       	      K   sø   |d krt d ƒn|}t|ƒ}| jj| }|d k	rR|j|f|ddœ|—Ž}|j|_n\||f|Ž}t|tjƒs~t	dt
|ƒ› d�ƒ‚|jj|jƒo˜|jj|jƒs®tdt
|ƒ› d�ƒ‚|j}| jj| j}||krêtdt
|ƒ› d|j› d|› �ƒ‚| j|ƒ | S )	NÚexpand)ÚaxisZresult_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:   )Úslicer   r>   r˜   Úapplyr<   r7   r-   r8   r9   Úreprr;   Úequalsr=   Úshaper«   )	r1   r"   rµ   rœ   r¥   r>   ÚresultZresult_shapeZexpected_shaper#   r#   r$   Ú_applyg  s(    

zStyler._applyc             K   s    | j jdd„ |||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)
        c             S   s
   t | dƒS )Nr¼   )Úgetattr)Úinstancer#   r#   r$   r3   ·  s    zStyler.apply.<locals>.<lambda>)r6   r†   )r1   r"   rµ   rœ   r¥   r#   r#   r$   r·   ˆ  s    .zStyler.applyc             K   sJ   t |f|Ž}|d kr"tjd d … }t|ƒ}| jj| j|ƒ}| j|ƒ | S )N)r   r-   Z
IndexSlicer   r>   r˜   Úapplymapr«   )r1   r"   rœ   r¥   r»   r#   r#   r$   Ú	_applymap»  s    
zStyler._applymapc             K   s   | j jdd„ ||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
        c             S   s
   t | dƒS )NrÀ   )r½   )r¾   r#   r#   r$   r3   Ý  s    z!Styler.applymap.<locals>.<lambda>)r6   r†   )r1   r"   rœ   r¥   r#   r#   r$   r¿   Ä  s    zStyler.applymapc                s.   ˆdkrd‰| j ‡ ‡‡fdd„fd|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.

        .. versionadded:: 0.21.0

        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
        NrM   c                s   ˆ | ƒrˆS ˆS )Nr#   )Úval)ÚcondÚotherrc   r#   r$   r3     s    zStyler.where.<locals>.<lambda>rœ   )r¿   )r1   rÂ   rc   rÃ   rœ   r¥   r#   )rÂ   rÃ   rc   r$   Úwhereá  s     zStyler.wherec             C   s
   || _ | S )z©
        Set the precision used to render.

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

        Returns
        -------
        self : Styler
        )r/   )r1   r/   r#   r#   r$   Úset_precision  s    zStyler.set_precisionc             C   s
   || _ | 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"> ...
        )rB   )r1   rq   r#   r#   r$   Úset_table_attributes  s    zStyler.set_table_attributesc             C   s   | j S )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
        )r6   )r1   r#   r#   r$   Úexport/  s    zStyler.exportc             C   s   | j j|ƒ | 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
        )r6   rˆ   )r1   Zstylesr#   r#   r$   Úuse?  s    z
Styler.usec             C   s
   || _ | S )z�
        Set the uuid for a Styler.

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

        Returns
        -------
        self : Styler
        )r?   )r1   r?   r#   r#   r$   Úset_uuidU  s    zStyler.set_uuidc             C   s
   || _ | S )z¢
        Set the caption on a Styler.

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

        Returns
        -------
        self : Styler
        )rA   )r1   rA   r#   r#   r$   Úset_captiond  s    zStyler.set_captionc             C   s
   || _ | 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')]}]
        ... )
        )r@   )r1   r@   r#   r#   r$   Úset_table_styless  s    zStyler.set_table_styles)r)   Úreturnc             C   s
   || _ | S )zÖ
        Set the missing data representation on a Styler.

        .. versionadded:: 1.0.0

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

        Returns
        -------
        self : Styler
        )r)   )r1   r)   r#   r#   r$   Ú
set_na_rep‘  s    zStyler.set_na_repc             C   s
   d| _ | S )z‹
        Hide any indices from rendering.

        .. versionadded:: 0.23.0

        Returns
        -------
        self : Styler
        T)rC   )r1   r#   r#   r$   Ú
hide_index¢  s    
zStyler.hide_indexc             C   s(   t |ƒ}| jj| }| jj|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
        )r   r>   r˜   r<   r™   rD   )r1   rœ   Z	hidden_dfr#   r#   r$   Úhide_columns¯  s    zStyler.hide_columnsc             C   s   t j| ƒrd|› �S dS )Nzbackground-color: rM   )r-   r.   )rª   Ú
null_colorr#   r#   r$   Ú_highlight_nullÈ  s    zStyler._highlight_nullÚredc             C   s   | j | j|d� | S )zÀ
        Shade the background ``null_color`` for missing values.

        Parameters
        ----------
        null_color : str

        Returns
        -------
        self : Styler
        )rÐ   )r¿   rÑ   )r1   rÐ   r#   r#   r$   Úhighlight_nullÌ  s    zStyler.highlight_nullÚPuBuçé&1¬Ú?)ÚvminÚvmaxc	       	      C   s6   t | 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µ   ÚlowÚhighÚtext_color_thresholdrÖ   r×   )r   r>   r   r·   Ú_background_gradient)	r1   rØ   rÙ   rÚ   rµ   rœ   rÛ   rÖ   r×   r#   r#   r$   Úbackground_gradientÛ  s    BzStyler.background_gradientc                s  t ˆttfƒ s*dˆ  ko"dkn   r6d}t|ƒ‚ttjƒ�Ô\}‰ |dkr\tj| j	ƒ ƒn|}	|dkrvtj
| j	ƒ ƒn|}
|
|	 }ˆ j|	||  |
||  ƒ}|jj|ƒ|| j	td�ƒƒ}dd„ ‰‡ ‡‡fdd	„‰| jdkrî‡fd
d„|D ƒS tj‡fdd„|D ƒ| j| jd�S W dQ R X dS )zD
        Color background in a range according to the data.
        r   r*   z3`text_color_threshold` must be a value from 0 to 1.N)Údtypec             S   s4   dd„ | dd… 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
                c             s   s*   | ]"}|d kr|d n
|d d V  qdS )g#Æ‚¤?g×£p=
×)@g)\�Âõ(¬?gáz®Gáð?g333333@Ng6¨£1ò?r#   )rf   r0   r#   r#   r$   r¡   [  s   zJStyler._background_gradient.<locals>.relative_luminance.<locals>.<genexpr>Né   g¼–�z6Ë?g¥,Cëâæ?g]mÅþ²{²?r#   )Úrgbar�   ÚgÚbr#   r#   r$   Úrelative_luminanceJ  s    z7Styler._background_gradient.<locals>.relative_luminancec                s0   ˆ| ƒˆk }|rdnd}dˆ j | ƒ› d|› d�S )Nz#f1f1f1z#000000zbackground-color: z;color: r§   )Zrgb2hex)rà   ZdarkZ
text_color)r   rã   rÛ   r#   r$   Úcss`  s    z(Styler._background_gradient.<locals>.cssc                s   g | ]}ˆ |ƒ‘qS r#   r#   )rf   rà   )rä   r#   r$   rg   f  s    z/Styler._background_gradient.<locals>.<listcomp>c                s   g | ]}‡ fd d„|D ƒ‘qS )c                s   g | ]}ˆ |ƒ‘qS r#   r#   )rf   rà   )rä   r#   r$   rg   i  s    z:Styler._background_gradient.<locals>.<listcomp>.<listcomp>r#   )rf   rr   )rä   r#   r$   rg   i  s    )r;   r<   )r7   ÚfloatÚintr=   r%   r&   rÝ   ÚnpÚnanminÚto_numpyÚnanmaxZ	NormalizeÚcmZget_cmapr:   r-   r8   r;   r<   )ÚsrØ   rÙ   rÚ   rÛ   rÖ   r×   Úmsgr   ÚsminÚsmaxÚrngZnormZrgbasr#   )r   rä   rã   rÛ   r$   rÜ   ,  s$    
zStyler._background_gradientc                s2   dj dd„ |jƒ D ƒƒ‰ ‡ fdd„}| 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§   c             s   s    | ]\}}|› d |› �V  qdS )z: Nr#   )rf   Úprª   r#   r#   r$   r¡   ƒ  s    z(Styler.set_properties.<locals>.<genexpr>c                s   ˆ S )Nr#   )r0   )Úvaluesr#   r$   r3   „  s    z'Styler.set_properties.<locals>.<lambda>)rœ   )r„   rš   r¿   )r1   rœ   r¥   r,   r#   )rò   r$   Úset_propertiesn  s    zStyler.set_propertieséd   c       	         s  |dkrt j| jƒ ƒn|}|dkr0t j| jƒ ƒn|}ˆ dkrRtd|ƒ}td|ƒ}n ˆ dkrrtt|ƒt|ƒƒ}| }ˆ| jtd�|  || d  }ˆ | || d  ‰‡fdd„‰‡ ‡‡‡fd	d
„‰| jdkrâ‡fdd„|D ƒS t	j
‡fdd„|D ƒ| j| jd�S dS )z4
        Draw bar chart in dataframe cells.
        NÚmidr   Úzero)rÞ   gê-�™—q=c                sh   d}|| krd|d7 }| dkr<|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.
            zwidth: 10em; height: 80%;z"background: linear-gradient(90deg,r   z transparent z.1fz%, ri   z%, transparent z%))Úmin)ÚstartÚendÚcolorrä   Úe)Úwidthr#   r$   Úcss_barš  s     
zStyler._bar.<locals>.css_barc                sV   t j| ƒrdS | ˆkrˆd nˆd }ˆ dkr:ˆd| |ƒS ˆt| ˆƒt| ˆƒ|ƒS d S )NrM   r*   r   Úleft)r-   r.   r÷   Úmax)r0   rú   )Úalignr   rý   rö   r#   r$   rä   §  s    
zStyler._bar.<locals>.cssr*   c                s   g | ]}ˆ |ƒ‘qS r#   r#   )rf   r0   )rä   r#   r$   rg   ´  s    zStyler._bar.<locals>.<listcomp>c                s   g | ]}‡ fd d„|D ƒ‘qS )c                s   g | ]}ˆ |ƒ‘qS r#   r#   )rf   r0   )rä   r#   r$   rg   ·  s    z*Styler._bar.<locals>.<listcomp>.<listcomp>r#   )rf   rr   )rä   r#   r$   rg   ·  s    )r;   r<   )rç   rè   ré   rê   r÷   rÿ   Úabsrå   r:   r-   r8   r;   r<   )	rì   r   r   rü   rÖ   r×   rî   rï   Znormedr#   )r   r   rä   rý   rü   rö   r$   Ú_bar‡  s$    
 
zStyler._barú#d65f5frþ   c          
   C   sˆ   |d
krt dƒ‚t|ƒs"||g}n2t|ƒdkr@|d |d g}nt|ƒdkrTt dƒ‚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
        rþ   rö   rõ   z.`align` must be one of {'left', 'zero',' mid'}r*   r   é   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×   )rþ   rö   rõ   )r=   r   rŒ   r   r>   r   r·   r  )r1   rœ   rµ   rú   rü   r   rÖ   r×   r#   r#   r$   Úbar¼  s*    7
z
Styler.barÚyellowc             C   s   | j |||dd�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œ   rú   rµ   Úmax_)Ú_highlight_handler)r1   rœ   rú   rµ   r#   r#   r$   Úhighlight_max  s    zStyler.highlight_maxc             C   s   | j |||dd�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œ   rú   rµ   r  )r  )r1   rœ   rú   rµ   r#   r#   r$   Úhighlight_min$  s    zStyler.highlight_minc             C   s*   t t| j|ƒƒ}| j| j||||d� | S )N)rú   rµ   rœ   r  )r   r   r>   r·   Ú_highlight_extrema)r1   rœ   rú   rµ   r  r#   r#   r$   r  :  s    zStyler._highlight_handlerc                sr   d|› �‰ |r"| t j| jƒ ƒk}n| t j| jƒ ƒk}| jdkrP‡ fdd„|D ƒS tjt j|ˆ dƒ| j| j	d�S dS )zD
        Highlight the min or max in a Series or DataFrame.
        zbackground-color: r*   c                s   g | ]}|rˆ nd ‘qS )rM   r#   )rf   rª   )Úattrr#   r$   rg   N  s    z-Styler._highlight_extrema.<locals>.<listcomp>rM   )r;   r<   N)
rç   rê   ré   rè   r:   r-   r8   rÄ   r;   r<   )r>   rú   r  Zextremar#   )r  r$   r  A  s    

zStyler._highlight_extremac                s0   t jt j|ƒ| jgƒ‰ G ‡ ‡fdd„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.
        c                   s"   e Zd Zej” d�Zej”ƒZdS )z-Styler.from_custom_template.<locals>.MyStyler)r(   N)r!   Ú
__module__Ú__qualname__r   ÚEnvironmentÚenvÚget_templater¤   r#   )r(   r�   r#   r$   ÚMyStyleri  s   r  )r   ZChoiceLoaderZFileSystemLoaderr(   )ÚclsZ
searchpathr�   r  r#   )r(   r�   r$   Úfrom_custom_templateT  s    zStyler.from_custom_templatec             O   s   t j| |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)r1   r"   r³   r¥   r#   r#   r$   r  o  s    EzStyler.pipe)NNNNNTN)rL   rM   NNTTNr   r   NTNrN   TN)NN)F)r   N)r   N)N)N)NN)rÒ   )rÔ   r   r   r   NrÕ   NN)rÔ   r   r   rÕ   NN)N)rô   NN)Nr   r  rô   rþ   NN)Nr  r   )Nr  r   )Nr  NT)r  T);r!   r  r  Ú__doc__r   ZPackageLoaderr(   r  r  r  r¤   r   r|   rG   rI   r   r   r   rJ   r•   r    rH   r«   r®   r¯   r±   r²   r¢   r¼   r·   rÀ   r¿   rÄ   rÅ   rÆ   rÇ   rÈ   rÉ   rÊ   rË   rÍ   rÎ   rÏ   ÚstaticmethodrÑ   rÓ   rå   rÝ   rÜ   ró   r  r  r	  r
  r  r  Úclassmethodr  r  r#   r#   r#   r$   r&   3   s¼   E
      +
               =I1
	
!
3
	

'
       H     :
6      
L


r&   c             C   s   || f|kS )z/
    Index -> {(idx_row, idx_col): bool}).
    r#   )Zidx_rowZidx_colÚlengthsr#   r#   r$   rŠ   ·  s    rŠ   c             C   s  | j tjddd�}|dkrg }i }| jdkrZx(t|ƒD ]\}}||kr6d|d|f< q6W |S xœt|ƒD ]�\}}x†t|ƒD ]z\}}tdƒs”d|||f< qv|tjk	r¸||kr¸|}	d|||	f< qv|tjk	rÔ|}	d|||	f< qv||krv|||	f  d7  < qvW qdW dd„ |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)ZsparsifyZadjoinr…   Nr*   r   zdisplay.multi_sparsec             S   s   i | ]\}}|d kr||“qS )r*   r#   )rf   ÚelementÚlengthr#   r#   r$   ú
<dictcomp>â  s   z&_get_level_lengths.<locals>.<dictcomp>)r    r   Z
no_defaultr€   r‡   r   rš   )r;   Zhidden_elementsZlevelsr  r�   rc   Zlvlrž   rr   Z
last_labelZnon_zero_lengthsr#   r#   r$   r~   ¾  s0    	

r~   )r)   c                sv   t ˆ tƒr‡ fdd„‰n"tˆ ƒr&ˆ ‰ndˆ › d�}t|ƒ‚ˆd krFˆS t ˆtƒr^‡‡fdd„S dˆ› d�}t|ƒ‚d S )Nc                s
   ˆ j | ƒS )N)r    )r0   )r^   r#   r$   r3   ë  s    z'_maybe_wrap_formatter.<locals>.<lambda>z,Expected a template string or callable, got z insteadc                s   t j| ƒrˆS ˆ | ƒS )N)r-   r.   )r0   )Úformatter_funcr)   r#   r$   r3   õ  s    zExpected a string, got )r7   r|   Úcallabler9   )r^   r)   rí   r#   )r^   r  r)   r$   r›   é  s    

r›   )N)>r  Úcollectionsr   Ú
contextlibr   r¬   Ú	functoolsr   Ú	itertoolsr   Útypingr   r   r   r	   r
   r   r   r   r?   r   Znumpyrç   Zpandas._configr   Zpandas._libsr   Zpandas.compat._optionalr   Zpandas.util._decoratorsr   Zpandas.core.dtypes.commonr   r'   r-   Zpandas.api.typesr   r   Zpandas.core.commonÚcoreÚcommonr‹   Zpandas.core.genericr   Zpandas.core.indexingr   r   r   Zmatplotlib.pyplotZpyplotr   Z
matplotlibr   r   r   r   r%   r&   rŠ   r~   r|   r›   r#   r#   r#   r$   Ú<module>   sT   (

           
+