B
    Y0d             	   @  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Zddl	m
Z
mZmZmZ ddlZddlZddlmZ ddlmZmZmZmZmZmZ dd	lmZ dd
l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'  m(Z) ddl*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 edddZ1ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 y ddl:m;Z; ddl<m=Z> dZ?W n e@k
r|   dZ?dZAY nX eddddZBG dd de5ZCdd d!d"d#d$d%d&ZDd8d)d)d)d*d*d+d,d-d.d/ZEd9d"d d0d0d1d#d2d3d4ZFd"d d d#d5d6d7ZGdS ):zF
Module for applying conditional formatting to DataFrames and Series.
    )annotations)contextmanagerN)partial)AnyCallableHashableSequence)
get_option)AxisFilePathOrBufferFrameOrSeriesFrameOrSeriesUnion
IndexLabelScalar)import_optional_dependency)doc)
IndexSlice
RangeIndex)is_list_like)generic)	DataFrameSeries)NDFrame)save_to_bufferjinja2z DataFrame.style requires jinja2.)extra)CSSProperties	CSSStylesStylerRendererSubsetTooltipsmaybe_convert_css_to_tuplesnon_reducing_slice)colorsTFz{0} requires matplotlib.r   )funcc             c  s$   t rttfV  ntt| jd S )N)has_mplpltr#   ImportErrorno_mpl_messageformat__name__)r$    r+   I/var/www/html/venv/lib/python3.7/site-packages/pandas/io/formats/style.py_mplG   s    r-   c                  s  e Zd ZdZddddd	d
d	dd	ddd	d	d fddZddddZdddddddZdddd	d dddZee	j
d ejd ddddd	d#d$dd%ddd	dd	ddd&d'd(d)d*Z
ddddd+ddddd,d-d+dd+d.d/d	d	d	dd	d
dddddd	dd0d1d2Zddddd+d+d3d/d	d	d	ddd4d5d6Zdd d7d8d9Zdd'd:d;d<Zddd d=d>d?Zd dd@dAZd ddBdCZd'ddDdEZddFdGdHd dIdJdKZddFdGdHd dIdLdMZddNdHd dOdPdQZddNdHd dOdRdSZddNdd	dHd dTdUdVZddWdXdYdZZdd d[d\d]Zd^dd_d`Zd^d dadbdcZdd dddedfZdgd dhdidjZddkddld dmdndoZ ddpddd dqdrdsZ!ddWdtdudvZ"ddHd dwdxdyZ#ddHd dwdzd{Z$ed|d}d~dd dddddGdHddddd d	ddZ%ee%d}d|ddddddddGdHdddd dddZ&ddHd dwddZ'e(dddddddddZ)ddHdGddddd dddZ*dddHd	d dddZ+ddHddGd	d dddZ,ddHddGd	d dddZ-ddHddGdddd	d dddZ.ddHddGddddd	d d	ddZ/e0dd	d	dddZ1dNdddZ2  Z3S )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, tuple, default None
        String caption to attach to the table. Tuple only used for LaTeX dual captions.
    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

    uuid_len : int, default 5
        If ``uuid`` is not specified, the length of the ``uuid`` to randomly generate
        expressed in hex characters, in range [0, 32].

        .. versionadded:: 1.2.0

    decimal : str, default "."
        Character used as decimal separator for floats, complex and integers

        .. versionadded:: 1.3.0

    thousands : str, optional, default None
        Character used as thousands separator for floats, complex and integers

        .. versionadded:: 1.3.0

    escape : str, optional
        Use 'html' to replace the characters ``&``, ``<``, ``>``, ``'``, and ``"``
        in cell display string with HTML-safe sequences.
        Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``,
        ``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with
        LaTeX-safe sequences.

        .. versionadded:: 1.3.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``
    NT   .r   z
int | NonezCSSStyles | Nonez
str | Nonezstr | tuple | Noneboolintstr)data	precisiontable_stylesuuidcaptiontable_attributescell_idsna_repuuid_lendecimal	thousandsescapec          	     s@   t  j|||	||||d || _|| _| jd ||||
|d d S )N)r4   r7   r<   r6   r9   r8   r:   )	formatterr5   r;   r?   r=   r>   )super__init__r5   r;   r)   )selfr4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   )	__class__r+   r,   rB      s"    zStyler.__init__)returnc             C  s   |   S )zB
        Hooks into Jupyter notebook rich display system.
        )render)rC   r+   r+   r,   _repr_html_   s    zStyler._repr_html_zbool | None)sparse_indexsparse_columnsrE   c             K  s0   |dkrt d}|dkr t d}| j||f|S )am  
        Render the ``Styler`` including all applied styles to HTML.

        Parameters
        ----------
        sparse_index : bool, optional
            Whether to sparsify the display of a hierarchical index. Setting to False
            will display each explicit level element in a hierarchical key for each row.
            Defaults to ``pandas.options.styler.sparse.index`` value.
        sparse_columns : bool, optional
            Whether to sparsify the display of a hierarchical index. Setting to False
            will display each explicit level element in a hierarchical key for each row.
            Defaults to ``pandas.options.styler.sparse.columns`` value.
        **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
        * table_styles
        * caption
        * table_attributes
        Nzstyler.sparse.indexzstyler.sparse.columns)r	   Z_render_html)rC   rH   rI   kwargsr+   r+   r,   rF      s
    2zStyler.renderr   zCSSProperties | None)ttipsprops	css_classrE   c             C  s\   | j std|jjr|jjs&td| jdkr8t | _|| j_|rL|| j_	|rX|| j_
| S )a
  
        Set the DataFrame of strings on ``Styler`` generating ``:hover`` tooltips.

        These string based tooltips are only applicable to ``<td>`` HTML elements,
        and cannot be used for column or index headers.

        .. versionadded:: 1.3.0

        Parameters
        ----------
        ttips : DataFrame
            DataFrame containing strings that will be translated to tooltips, mapped
            by identical column and index values that must exist on the underlying
            Styler data. None, NaN values, and empty strings will be ignored and
            not affect the rendered HTML.
        props : list-like or str, optional
            List of (attr, value) tuples or a valid CSS string. If ``None`` adopts
            the internal default values described in notes.
        css_class : str, optional
            Name of the tooltip class used in CSS, should conform to HTML standards.
            Only useful if integrating tooltips with external CSS. If ``None`` uses the
            internal default value 'pd-t'.

        Returns
        -------
        self : Styler

        Notes
        -----
        Tooltips are created by adding `<span class="pd-t"></span>` to each data cell
        and then manipulating the table level CSS to attach pseudo hover and pseudo
        after selectors to produce the required the results.

        The default properties for the tooltip CSS class are:

        - visibility: hidden
        - position: absolute
        - z-index: 1
        - background-color: black
        - color: white
        - transform: translate(-20px, -20px)

        The property 'visibility: hidden;' is a key prerequisite to the hover
        functionality, and should always be included in any manual properties
        specification, using the ``props`` argument.

        Tooltips are not designed to be efficient, and can add large amounts of
        additional HTML for larger tables, since they also require that ``cell_ids``
        is forced to `True`.

        Examples
        --------
        Basic application

        >>> df = pd.DataFrame(data=[[0, 1], [2, 3]])
        >>> ttips = pd.DataFrame(
        ...    data=[["Min", ""], [np.nan, "Max"]], columns=df.columns, index=df.index
        ... )
        >>> s = df.style.set_tooltips(ttips).render()

        Optionally controlling the tooltip visual display

        >>> df.style.set_tooltips(ttips, css_class='tt-add', props=[
        ...     ('visibility', 'hidden'),
        ...     ('position', 'absolute'),
        ...     ('z-index', 1)])
        >>> df.style.set_tooltips(ttips, css_class='tt-add',
        ...     props='visibility:hidden; position:absolute; z-index:1;')
        z1Tooltips can only render with 'cell_ids' is True.z=Tooltips render only if `ttips` has unique index and columns.N)r:   NotImplementedErrorindex	is_uniquecolumnsKeyErrortooltipsr    Ztt_dataZclass_properties
class_name)rC   rK   rL   rM   r+   r+   r,   set_tooltips  s    K
zStyler.set_tooltipsstorage_options)klassrV   Sheet1 r   infzSequence[Hashable] | NonezSequence[Hashable] | boolzIndexLabel | Noneztuple[int, int] | NoneNone)
sheet_namer;   float_formatrQ   headerrO   index_labelstartrowstartcolenginemerge_cellsencodinginf_repverbosefreeze_panesrE   c             C  s@   ddl m} || ||||||||d	}|j|||	|
||d d S )Nr   )ExcelFormatter)r;   colsr^   r]   rO   r_   rc   re   )r\   r`   ra   rg   rb   )Zpandas.io.formats.excelrh   write)rC   Zexcel_writerr\   r;   r]   rQ   r^   rO   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   r@   r+   r+   r,   to_excelq  s$    zStyler.to_excelFcr)column_formatpositionposition_floathruleslabelr8   rH   rI   multirow_alignmulticol_alignsiunitxrd   convert_csszFilePathOrBuffer[str] | None)bufrn   ro   rp   rq   rr   r8   rH   rI   rs   rt   ru   rd   rv   c            C  s  | j dd}| jdk	r&dd | jD ng }|dk	rP|jdd| dgd	d
 nd|krZn| jj}tt| jjd| j_| j j }|| j_| j	rdnd| jj
j }x>t| jjD ].\}}|| jkr|||kr|sdqdnd7 }qW |jdd| dgd	d
 |r&|jdd| dgd	d
 |rb|dkrFtd| d|jdd| dgd	d
 |r|jdddddddddgd	d
 |r|jdd|dd ddgd	d
 |r|| |dkrtd}|	dkrtd }	|j||	|
||d!}t|||d"S )#u4  
        Write Styler to a file, buffer or string in LaTeX format.

        .. versionadded:: 1.3.0

        Parameters
        ----------
        buf : str, Path, or StringIO-like, optional, default None
            Buffer to write to. If ``None``, the output is returned as a string.
        column_format : str, optional
            The LaTeX column specification placed in location:

            \\begin{tabular}{<column_format>}

            Defaults to 'l' for index and
            non-numeric data columns, and, for numeric data columns,
            to 'r' by default, or 'S' if ``siunitx`` is ``True``.
        position : str, optional
            The LaTeX positional argument (e.g. 'h!') for tables, placed in location:

            \\begin{table}[<position>]
        position_float : {"centering", "raggedleft", "raggedright"}, optional
            The LaTeX float command placed in location:

            \\begin{table}[<position>]

            \\<position_float>
        hrules : bool, default False
            Set to `True` to add \\toprule, \\midrule and \\bottomrule from the
            {booktabs} LaTeX package.
        label : str, optional
            The LaTeX label included as: \\label{<label>}.
            This is used with \\ref{<label>} in the main .tex file.
        caption : str, tuple, optional
            If string, the LaTeX table caption included as: \\caption{<caption>}.
            If tuple, i.e ("full caption", "short caption"), the caption included
            as: \\caption[<caption[1]>]{<caption[0]>}.
        sparse_index : bool, optional
            Whether to sparsify the display of a hierarchical index. Setting to False
            will display each explicit level element in a hierarchical key for each row.
            Defaults to ``pandas.options.styler.sparse.index`` value.
        sparse_columns : bool, optional
            Whether to sparsify the display of a hierarchical index. Setting to False
            will display each explicit level element in a hierarchical key for each row.
            Defaults to ``pandas.options.styler.sparse.columns`` value.
        multirow_align : {"c", "t", "b"}
            If sparsifying hierarchical MultiIndexes whether to align text centrally,
            at the top or bottom.
        multicol_align : {"r", "c", "l"}
            If sparsifying hierarchical MultiIndex columns whether to align text at
            the left, centrally, or at the right.
        siunitx : bool, default False
            Set to ``True`` to structure LaTeX compatible with the {siunitx} package.
        encoding : str, default "utf-8"
            Character encoding setting.
        convert_css : bool, default False
            Convert simple cell-styles from CSS to LaTeX format. Any CSS not found in
            conversion table is dropped. A style can be forced by adding option
            `--latex`. See notes.

        Returns
        -------
        str or None
            If `buf` is None, returns the result as a string. Otherwise returns `None`.

        See Also
        --------
        Styler.format: Format the text display value of cells.

        Notes
        -----
        **Latex Packages**

        For the following features we recommend the following LaTeX inclusions:

        ===================== ==========================================================
        Feature               Inclusion
        ===================== ==========================================================
        sparse columns        none: included within default {tabular} environment
        sparse rows           \\usepackage{multirow}
        hrules                \\usepackage{booktabs}
        colors                \\usepackage[table]{xcolor}
        siunitx               \\usepackage{siunitx}
        bold (with siunitx)   | \\usepackage{etoolbox}
                              | \\robustify\\bfseries
                              | \\sisetup{detect-all = true}  *(within {document})*
        italic (with siunitx) | \\usepackage{etoolbox}
                              | \\robustify\\itshape
                              | \\sisetup{detect-all = true}  *(within {document})*
        ===================== ==========================================================

        **Cell Styles**

        LaTeX styling can only be rendered if the accompanying styling functions have
        been constructed with appropriate LaTeX commands. All styling
        functionality is built around the concept of a CSS ``(<attribute>, <value>)``
        pair (see `Table Visualization <../../user_guide/style.ipynb>`_), and this
        should be replaced by a LaTeX
        ``(<command>, <options>)`` approach. Each cell will be styled individually
        using nested LaTeX commands with their accompanied options.

        For example the following code will highlight and bold a cell in HTML-CSS:

        >>> df = pd.DataFrame([[1,2], [3,4]])
        >>> s = df.style.highlight_max(axis=None,
        ...                            props='background-color:red; font-weight:bold;')
        >>> s.render()

        The equivalent using LaTeX only commands is the following:

        >>> s = df.style.highlight_max(axis=None,
        ...                            props='cellcolor:{red}; bfseries: ;')
        >>> s.to_latex()

        Internally these structured LaTeX ``(<command>, <options>)`` pairs
        are translated to the
        ``display_value`` with the default structure:
        ``\<command><options> <display_value>``.
        Where there are multiple commands the latter is nested recursively, so that
        the above example highlighed cell is rendered as
        ``\cellcolor{red} \bfseries 4``.

        Occasionally this format does not suit the applied command, or
        combination of LaTeX packages that is in use, so additional flags can be
        added to the ``<options>``, within the tuple, to result in different
        positions of required braces (the **default** being the same as ``--nowrap``):

        =================================== ============================================
        Tuple Format                           Output Structure
        =================================== ============================================
        (<command>,<options>)               \\<command><options> <display_value>
        (<command>,<options> ``--nowrap``)  \\<command><options> <display_value>
        (<command>,<options> ``--rwrap``)   \\<command><options>{<display_value>}
        (<command>,<options> ``--wrap``)    {\\<command><options> <display_value>}
        (<command>,<options> ``--lwrap``)   {\\<command><options>} <display_value>
        (<command>,<options> ``--dwrap``)   {\\<command><options>}{<display_value>}
        =================================== ============================================

        For example the `textbf` command for font-weight
        should always be used with `--rwrap` so ``('textbf', '--rwrap')`` will render a
        working cell, wrapped with braces, as ``\textbf{<display_value>}``.

        A more comprehensive example is as follows:

        >>> df = pd.DataFrame([[1, 2.2, "dogs"], [3, 4.4, "cats"], [2, 6.6, "cows"]],
        ...                   index=["ix1", "ix2", "ix3"],
        ...                   columns=["Integers", "Floats", "Strings"])
        >>> s = df.style.highlight_max(
        ...     props='cellcolor:[HTML]{FFFF00}; color:{red};'
        ...           'textit:--rwrap; textbf:--rwrap;'
        ... )
        >>> s.to_latex()

        .. figure:: ../../_static/style/latex_1.png

        **Table Styles**

        Internally Styler uses its ``table_styles`` object to parse the
        ``column_format``, ``position``, ``position_float``, and ``label``
        input arguments. These arguments are added to table styles in the format:

        .. code-block:: python

            set_table_styles([
                {"selector": "column_format", "props": f":{column_format};"},
                {"selector": "position", "props": f":{position};"},
                {"selector": "position_float", "props": f":{position_float};"},
                {"selector": "label", "props": f":{{{label.replace(':','§')}}};"}
            ], overwrite=False)

        Exception is made for the ``hrules`` argument which, in fact, controls all three
        commands: ``toprule``, ``bottomrule`` and ``midrule`` simultaneously. Instead of
        setting ``hrules`` to ``True``, it is also possible to set each
        individual rule definition, by manually setting the ``table_styles``,
        for example below we set a regular ``toprule``, set an ``hline`` for
        ``bottomrule`` and exclude the ``midrule``:

        .. code-block:: python

            set_table_styles([
                {'selector': 'toprule', 'props': ':toprule;'},
                {'selector': 'bottomrule', 'props': ':hline;'},
            ], overwrite=False)

        If other ``commands`` are added to table styles they will be detected, and
        positioned immediately above the '\\begin{tabular}' command. For example to
        add odd and even row coloring, from the {colortbl} package, in format
        ``\rowcolors{1}{pink}{red}``, use:

        .. code-block:: python

            set_table_styles([
                {'selector': 'rowcolors', 'props': ':{1}{pink}{red};'}
            ], overwrite=False)

        A more comprehensive example using these arguments is as follows:

        >>> df.columns = pd.MultiIndex.from_tuples([
        ...     ("Numeric", "Integers"),
        ...     ("Numeric", "Floats"),
        ...     ("Non-Numeric", "Strings")
        ... ])
        >>> df.index = pd.MultiIndex.from_tuples([
        ...     ("L0", "ix1"), ("L0", "ix2"), ("L1", "ix3")
        ... ])
        >>> s = df.style.highlight_max(
        ...     props='cellcolor:[HTML]{FFFF00}; color:{red}; itshape:; bfseries:;'
        ... )
        >>> s.to_latex(
        ...     column_format="rrrrr", position="h", position_float="centering",
        ...     hrules=True, label="table:5", caption="Styled LaTeX Table",
        ...     multirow_align="t", multicol_align="r"
        ... )

        .. figure:: ../../_static/style/latex_2.png

        **Formatting**

        To format values :meth:`Styler.format` should be used prior to calling
        `Styler.to_latex`, as well as other methods such as :meth:`Styler.hide_index`
        or :meth:`Styler.hide_columns`, for example:

        >>> s.clear()
        >>> s.table_styles = []
        >>> s.caption = None
        >>> s.format({
        ...    ("Numeric", "Integers"): '\${}',
        ...    ("Numeric", "Floats"): '{:.3f}',
        ...    ("Non-Numeric", "Strings"): str.upper
        ... })
        >>> s.to_latex()
        \begin{tabular}{llrrl}
        {} & {} & \multicolumn{2}{r}{Numeric} & {Non-Numeric} \\
        {} & {} & {Integers} & {Floats} & {Strings} \\
        \multirow[c]{2}{*}{L0} & ix1 & \\$1 & 2.200 & DOGS \\
         & ix2 & \$3 & 4.400 & CATS \\
        L1 & ix3 & \$2 & 6.600 & COWS \\
        \end{tabular}

        **CSS Conversion**

        This method can convert a Styler constructured with HTML-CSS to LaTeX using
        the following limited conversions.

        ================== ==================== ============= ==========================
        CSS Attribute      CSS value            LaTeX Command LaTeX Options
        ================== ==================== ============= ==========================
        font-weight        | bold               | bfseries
                           | bolder             | bfseries
        font-style         | italic             | itshape
                           | oblique            | slshape
        background-color   | red                cellcolor     | {red}--lwrap
                           | #fe01ea                          | [HTML]{FE01EA}--lwrap
                           | #f0e                             | [HTML]{FF00EE}--lwrap
                           | rgb(128,255,0)                   | [rgb]{0.5,1,0}--lwrap
                           | rgba(128,0,0,0.5)                | [rgb]{0.5,0,0}--lwrap
                           | rgb(25%,255,50%)                 | [rgb]{0.25,1,0.5}--lwrap
        color              | red                color         | {red}
                           | #fe01ea                          | [HTML]{FE01EA}
                           | #f0e                             | [HTML]{FF00EE}
                           | rgb(128,255,0)                   | [rgb]{0.5,1,0}
                           | rgba(128,0,0,0.5)                | [rgb]{0.5,0,0}
                           | rgb(25%,255,50%)                 | [rgb]{0.25,1,0.5}
        ================== ==================== ============= ==========================

        It is also possible to add user-defined LaTeX only styles to a HTML-CSS Styler
        using the ``--latex`` flag, and to add LaTeX parsing options that the
        converter will detect within a CSS-comment.

        >>> df = pd.DataFrame([[1]])
        >>> df.style.set_properties(
        ...     **{"font-weight": "bold /* --dwrap */", "Huge": "--latex--rwrap"}
        ... ).to_latex(convert_css=True)
        \begin{tabular}{lr}
        {} & {0} \\
        0 & {\bfseries}{\Huge{1}} \\
        \end{tabular}
        T)deepcopyNc             S  s   g | ]}|d  qS )selectorr+   ).0styler+   r+   r,   
<listcomp>  s    z#Styler.to_latex.<locals>.<listcomp>rn   :)ry   rL   F)	overwrite)stoprY   lrm   Sro   )ZraggedrightZ
raggedleftZ	centeringzR`position_float` should be one of 'raggedright', 'raggedleft', 'centering', got: ''rp   Ztoprulez:topruleZmidrulez:midruleZ
bottomrulez:bottomrulerr   z:{   §}zstyler.sparse.indexzstyler.sparse.columns)rH   rI   rs   rt   rv   )rw   rd   )_copyr6   set_table_stylesr4   rQ   r   lenZ_get_numeric_dataZto_listhide_index_rO   nlevels	enumeratehidden_columns
ValueErrorreplaceset_captionr	   Z_render_latexr   )rC   rw   rn   ro   rp   rq   rr   r8   rH   rI   rs   rt   ru   rd   rv   objZtable_selectorsZ_original_columnsZnumeric_colsci_latexr+   r+   r,   to_latex  sr      *






zStyler.to_latex)
table_uuidr9   rd   doctype_htmlexclude_styles)rw   r   r9   rd   r   r   c            C  sN   |r|  | |r| | | j||r*|nd|d}t|||dk	rF|nddS )aU  
        Write Styler to a file, buffer or string in HTML-CSS format.

        .. versionadded:: 1.3.0

        Parameters
        ----------
        buf : str, Path, or StringIO-like, optional, default None
            Buffer to write to. If ``None``, the output is returned as a string.
        table_uuid : str, optional
            Id attribute assigned to the <table> HTML element in the format:

            ``<table id="T_<table_uuid>" ..>``

            If not given uses Styler's initially assigned value.
        table_attributes : str, optional
            Attributes to assign within the `<table>` HTML element in the format:

            ``<table .. <table_attributes> >``

            If not given defaults to Styler's preexisting value.
        encoding : str, optional
            Character encoding setting for file output, and HTML meta tags,
            defaults to "utf-8" if None.
        doctype_html : bool, default False
            Whether to output a fully structured HTML file including all
            HTML elements, or just the core ``<style>`` and ``<table>`` elements.
        exclude_styles : bool, default False
            Whether to include the ``<style>`` element and all associated element
            ``class`` and ``id`` identifiers, or solely the ``<table>`` element without
            styling identifiers.

        Returns
        -------
        str or None
            If `buf` is None, returns the result as a string. Otherwise returns `None`.

        See Also
        --------
        DataFrame.to_html: Write a DataFrame to a file, buffer or string in HTML format.
        zutf-8)r   rd   r   N)rw   rd   )set_uuidset_table_attributesrF   r   )rC   rw   r   r9   rd   r   r   htmlr+   r+   r,   to_html  s    3


zStyler.to_html)classesrE   c             C  s   |j jr|jjstd|| j}xZt| D ]J\}}x@t|dd D ],\}}t	|sL|dksLt
|| j||f< qLW q2W | S )a  
        Set the DataFrame of strings added to the ``class`` attribute of ``<td>``
        HTML elements.

        Parameters
        ----------
        classes : DataFrame
            DataFrame containing strings that will be translated to CSS classes,
            mapped by identical column and index key values that must exist on the
            underlying Styler data. None, NaN values, and empty strings will
            be ignored and not affect the rendered HTML.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.set_table_styles: Set the table styles included within the ``<style>``
            HTML element.
        Styler.set_table_attributes: Set the table attributes added to the ``<table>``
            HTML element.

        Notes
        -----
        Can be used in combination with ``Styler.set_table_styles`` to define an
        internal CSS solution without reference to external CSS files.

        Examples
        --------
        >>> df = pd.DataFrame(data=[[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"])
        >>> classes = pd.DataFrame([
        ...     ["min-val red", "", "blue"],
        ...     ["red", None, "blue max-val"]
        ... ], index=df.index, columns=df.columns)
        >>> df.style.set_td_classes(classes)

        Using `MultiIndex` columns and a `classes` `DataFrame` as a subset of the
        underlying,

        >>> df = pd.DataFrame([[1,2],[3,4]], index=["a", "b"],
        ...     columns=[["level0", "level0"], ["level1a", "level1b"]])
        >>> classes = pd.DataFrame(["min-val"], index=["a"],
        ...     columns=[["level0"],["level1a"]])
        >>> df.style.set_td_classes(classes)

        Form of the output with new additional css classes,

        >>> df = pd.DataFrame([[1]])
        >>> css = pd.DataFrame([["other-class"]])
        >>> s = Styler(df, uuid="_", cell_ids=False).set_td_classes(css)
        >>> s.hide_index().render()
        '<style type="text/css"></style>'
        '<table id="T__">'
        '  <thead>'
        '    <tr><th class="col_heading level0 col0" >0</th></tr>'
        '  </thead>'
        '  <tbody>'
        '    <tr><td class="data row0 col0 other-class" >1</td></tr>'
        '  </tbody>'
        '</table>'
        z>Classes render only if `classes` has unique index and columns.   NrY   )rO   rP   rQ   rR   reindex_liker4   r   
itertuplespdisnar3   cell_context)rC   r   rm   Zrow_tuprl   valuer+   r+   r,   set_td_classesa  s    ?zStyler.set_td_classes)attrsrE   c             C  s   | j jr| jjstdxf|jD ]\}xV||g  D ]D\}}|sBq4t|}| j || j| }}| j||f | q4W q W dS )a  
        Update the state of the ``Styler`` for data cells.

        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.
        zS`Styler.apply` and `.applymap` are not compatible with non-unique index or columns.N)	rO   rP   rQ   rR   r   r!   Zget_locctxextend)rC   r   ZcnZrnrl   Zcss_listijr+   r+   r,   _update_ctx  s    zStyler._update_ctx)rx   rE   c             C  s   t | j| jd}dddddg}ddd	d
ddddg}x|D ]}t||t| | q8W x0|D ](}t| |}t|||rzt|n| qXW |S )a  
        Copies a Styler, allowing for deepcopy or shallow copy

        Copying a Styler aims to recreate a new Styler object which contains the same
        data and styles as the original.

        Data dependent attributes [copied and NOT exported]:
          - formatting (._display_funcs)
          - hidden index values or column values (.hidden_rows, .hidden_columns)
          - tooltips
          - cell_context (cell css classes)
          - ctx (cell css styles)
          - caption

        Non-data dependent attributes [copied and exported]:
          - hidden index state and hidden columns state (.hide_index_, .hide_columns_)
          - table_attributes
          - table_styles
          - applied styles (_todo)

        )r<   r   hide_columns_r9   r:   r8   Z_display_funcshidden_rowsr   r   r   _todor6   rS   )r.   r4   r<   setattrgetattrcopyrx   )rC   rx   ZstylerZshallowdeepattrvalr+   r+   r,   r     s,    



zStyler._copyc             C  s   | j ddS )NF)rx   )r   )rC   r+   r+   r,   __copy__  s    zStyler.__copy__c             C  s   | j ddS )NT)rx   )r   )rC   memor+   r+   r,   __deepcopy__  s    zStyler.__deepcopy__c             C  s4   | j   d| _| j  | j  d| _g | _dS )zf
        Reset the ``Styler``, removing any previously applied styles.

        Returns None.
        NF)r   clearrS   r   r   r   r   )rC   r+   r+   r,   r     s    


zStyler.clearzCallable[..., Styler]zAxis | NonezSubset | None)r$   axissubsetrE   c             K  s8  |d krt d n|}t|}| jj| }|d k	rR|j|f|dd|}|j|_n||f|}t|tst|tj	st
dt| d|j|jkstdt| d|j d|j t||j|jd}n0|j|jr|j|jstdt| d	|j|jkr*tdt| d
|j d|j | | | S )Nexpand)r   Zresult_typez	Function zP must return a DataFrame or ndarray when passed to `Styler.apply` with axis=Nonez6 returned ndarray with wrong shape.
Result has shape: z
Expected shape: )rO   rQ   z
Result of z3 must have identical index and columns as the inputz- returned the wrong shape.
Result has shape: z
Expected shape:   )slicer"   r4   locapplyrQ   
isinstancer   npndarray	TypeErrorreprshaper   rO   equalsr   )rC   r$   r   r   rJ   r4   resultr+   r+   r,   _apply  s.    

  
zStyler._applyc             K  s    | j dd |||f|f | S )a
  
        Apply a CSS-styling function column-wise, row-wise, or table-wise.

        Updates the HTML representation with the result.

        Parameters
        ----------
        func : function
            ``func`` should take a Series if ``axis`` in [0,1] and return an object
            of same length, also with identical index if the object is a Series.
            ``func`` should take a DataFrame if ``axis`` is ``None`` and return either
            an ndarray with the same shape or a DataFrame with identical columns and
            index.

            .. versionchanged:: 1.3.0

        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 : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        **kwargs : dict
            Pass along to ``func``.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.applymap: Apply a CSS-styling function elementwise.

        Notes
        -----
        The elements of the output of ``func`` should be CSS styles as strings, in the
        format 'attribute: value; attribute2: value2; ...' or,
        if nothing is to be applied to that element, an empty string or ``None``.

        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, color):
        ...     return np.where(x == np.nanmax(x.to_numpy()), f"color: {color};", None)
        >>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
        >>> df.style.apply(highlight_max, color='red')
        >>> df.style.apply(highlight_max, color='blue', axis=1)
        >>> df.style.apply(highlight_max, color='green', axis=None)

        Using ``subset`` to restrict application to a single column or multiple columns

        >>> df.style.apply(highlight_max, color='red', subset="A")
        >>> df.style.apply(highlight_max, color='red', subset=["A", "B"])

        Using a 2d input to ``subset`` to select rows in addition to columns

        >>> df.style.apply(highlight_max, color='red', subset=([0,1,2], slice(None))
        >>> df.style.apply(highlight_max, color='red', subset=(slice(0,5,2), "A")
        c             S  s
   t | dS )Nr   )r   )instancer+   r+   r,   <lambda>      zStyler.apply.<locals>.<lambda>)r   append)rC   r$   r   r   rJ   r+   r+   r,   r   A  s    GzStyler.applyr   )r$   r   rE   c             K  sH   t |f|}|d kr td d  }t|}| jj| |}| | | S )N)r   r   r"   r4   r   applymapr   )rC   r$   r   rJ   r   r+   r+   r,   	_applymap  s    
zStyler._applymapc             K  s   | j dd ||f|f | S )a  
        Apply a CSS-styling function elementwise.

        Updates the HTML representation with the result.

        Parameters
        ----------
        func : function
            ``func`` should take a scalar and return a scalar.
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        **kwargs : dict
            Pass along to ``func``.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.

        Notes
        -----
        The elements of the output of ``func`` should be CSS styles as strings, in the
        format 'attribute: value; attribute2: value2; ...' or,
        if nothing is to be applied to that element, an empty string or ``None``.

        Examples
        --------
        >>> def color_negative(v, color):
        ...     return f"color: {color};" if v < 0 else None
        >>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
        >>> df.style.applymap(color_negative, color='red')

        Using ``subset`` to restrict application to a single column or multiple columns

        >>> df.style.applymap(color_negative, color='red', subset="A")
        >>> df.style.applymap(color_negative, color='red', subset=["A", "B"])

        Using a 2d input to ``subset`` to select rows in addition to columns

        >>> df.style.applymap(color_negative, color='red', subset=([0,1,2], slice(None))
        >>> df.style.applymap(color_negative, color='red', subset=(slice(0,5,2), "A")
        c             S  s
   t | dS )Nr   )r   )r   r+   r+   r,   r     r   z!Styler.applymap.<locals>.<lambda>)r   r   )rC   r$   r   rJ   r+   r+   r,   r     s    2zStyler.applymap)condr   otherr   rE   c               s8   t jdtdd dkrd| j fdd|dS )	a'  
        Apply CSS-styles based on a conditional function elementwise.

        .. deprecated:: 1.3.0

        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 optional keyword arguments, and return
            a boolean.
        value : str
            Applied when ``cond`` returns true.
        other : str
            Applied when ``cond`` returns false.
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        **kwargs : dict
            Pass along to ``cond``.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.applymap: Apply a CSS-styling function elementwise.
        Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.

        Notes
        -----
        This method is deprecated.

        This method is a convenience wrapper for :meth:`Styler.applymap`, which we
        recommend using instead.

        The example:

        >>> df = pd.DataFrame([[1, 2], [3, 4]])
        >>> def cond(v, limit=4):
        ...     return v > 1 and v != limit
        >>> df.style.where(cond, value='color:green;', other='color:red;')

        should be refactored to:

        >>> def style_func(v, value, other, limit=4):
        ...     cond = v > 1 and v != limit
        ...     return value if cond else other
        >>> df.style.applymap(style_func, value='color:green;', other='color:red;')
        z:this method is deprecated in favour of `Styler.applymap()`   )
stacklevelNrY   c               s    | frS S )Nr+   )r   )r   rJ   r   r   r+   r,   r     r   zStyler.where.<locals>.<lambda>)r   )warningswarnFutureWarningr   )rC   r   r   r   r   rJ   r+   )r   rJ   r   r   r,   where  s    >zStyler.wherer   )r5   rE   c             C  s&   t jdtdd || _| j|| jdS )a$  
        Set the precision used to display values.

        .. deprecated:: 1.3.0

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

        Returns
        -------
        self : Styler

        Notes
        -----
        This method is deprecated see `Styler.format`.
        zDthis method is deprecated in favour of `Styler.format(precision=..)`r   )r   )r5   r;   )r   r   r   r5   r)   r;   )rC   r5   r+   r+   r,   set_precision  s    zStyler.set_precision)
attributesrE   c             C  s
   || _ | S )a  
        Set the table attributes added to the ``<table>`` HTML element.

        These are items in addition to automatic (by default) ``id`` attribute.

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

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.set_table_styles: Set the table styles included within the ``<style>``
            HTML element.
        Styler.set_td_classes: Set the DataFrame of strings added to the ``class``
            attribute of ``<td>`` HTML elements.

        Examples
        --------
        >>> df = pd.DataFrame(np.random.randn(10, 4))
        >>> df.style.set_table_attributes('class="pure-table"')
        # ... <table class="pure-table"> ...
        )r9   )rC   r   r+   r+   r,   r   5  s    zStyler.set_table_attributesz"list[tuple[Callable, tuple, dict]]c             C  s   | j S )a  
        Export the styles applied to the current ``Styler``.

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

        Returns
        -------
        styles : list

        See Also
        --------
        Styler.use: Set the styles on the current ``Styler``.
        )r   )rC   r+   r+   r,   exportS  s    zStyler.export)stylesrE   c             C  s   | 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 : Export the styles to applied to the current ``Styler``.
        )r   r   )rC   r   r+   r+   r,   usec  s    z
Styler.use)r7   rE   c             C  s
   || _ | S )a  
        Set the uuid applied to ``id`` attributes of HTML elements.

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

        Returns
        -------
        self : Styler

        Notes
        -----
        Almost all HTML elements within the table, and including the ``<table>`` element
        are assigned ``id`` attributes. The format is ``T_uuid_<extra>`` where
        ``<extra>`` is typically a more specific identifier, such as ``row1_col2``.
        )r7   )rC   r7   r+   r+   r,   r   y  s    zStyler.set_uuidzstr | tuple)r8   rE   c             C  s
   || _ | S )a  
        Set the text added to a ``<caption>`` HTML element.

        Parameters
        ----------
        caption : str, tuple
            For HTML output either the string input is used or the first element of the
            tuple. For LaTeX the string input provides a caption and the additional
            tuple input allows for full captions and short captions, in that order.

        Returns
        -------
        self : Styler
        )r8   )rC   r8   r+   r+   r,   r     s    zStyler.set_captionr
   zlist[int] | None)r   
pixel_sizelevelsrE   c          
   C  s,  |dkr$d| j j }}|sdn|}n,|dkrHd| j j }}|sBdn|}ntdd}t|tjs|dkrd	|d
 dg}| jjd dk	r|d| d |d d< |d|d| d| d d nd|d dd|d dg}n:t	t
|j}|r t|n|}|dkrg }xHt|D ]<\}}	|d|	d  d|d||  d| d d qW tdd | jjD s|d|jd  d|d|d |  d| d d npg }xjt|D ]^\}}	|d||  d| d | d }
|d!|	d  d"|
d# dd$|	 |
d% dg qW | j|d&d'S )(a4  
        Add CSS to permanently display the index or column headers in a scrolling frame.

        Parameters
        ----------
        axis : {0 or 'index', 1 or 'columns'}, default 0
            Whether to make the index or column headers sticky.
        pixel_size : int, optional
            Required to configure the width of index cells or the height of column
            header cells when sticking a MultiIndex (or with a named Index).
            Defaults to 75 and 25 respectively.
        levels : list of int
            If ``axis`` is a MultiIndex the specific levels to stick. If ``None`` will
            stick all levels.

        Returns
        -------
        self : Styler

        Notes
        -----
        This method uses the CSS 'position: sticky;' property to display. It is
        designed to work with visible axes, therefore both:

          - `styler.set_sticky(axis="index").hide_index()`
          - `styler.set_sticky(axis="columns").hide_columns()`

        may produce strange behaviour due to CSS controls with missing elements.
        )r   rO   r   K   )r   rQ   r      z0`axis` must be one of {0, 1, 'index', 'columns'}z(position:sticky; background-color:white;zthead tr:nth-child(1) thztop:0px; z-index:2;)ry   rL   Nztop:0px; z-index:2; height:zpx;rL   zthead tr:nth-child(2) thztop:zpx; z-index:2; height:zpx; zthead tr th:nth-child(1)zleft:0px; z-index:3 !important;ztbody tr th:nth-child(1)zleft:0px; z-index:1;zthead tr:nth-child(z) thzpx; height:zpx; z-index:2;c             s  s   | ]}|d kV  qd S )Nr+   )rz   namer+   r+   r,   	<genexpr>  s    z$Styler.set_sticky.<locals>.<genexpr>zleft:zpx; min-width:zpx; max-width:zthead tr th:nth-child()zz-index:3 !important;ztbody tr th.levelz
z-index:1;F)r~   )r4   rO   rQ   r   r   r   Z
MultiIndexnamesr   listranger   sortedr   allr   r   )rC   r   r   r   r   rL   r   Z	range_idxr   levelZprops_r+   r+   r,   
set_sticky  s\    #	

$$
zStyler.set_stickyz dict[Any, CSSStyles] | CSSStyles)r6   r   r~   rE   c               s~   t |trJ|dkr"| jjd  n| jjd   fdd| D }ndd |D }|st| jdk	rt| j| n|| _| S )a  
        Set the table styles included within the ``<style>`` HTML element.

        This function can be used to style the entire table, columns, rows or
        specific HTML selectors.

        Parameters
        ----------
        table_styles : list or dict
            If supplying a 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)``.
            If supplying a dict, the dict keys should correspond to
            column names or index values, depending upon the specified
            `axis` argument. These will be mapped to row or col CSS
            selectors. MultiIndex values as dict keys should be
            in their respective tuple form. The dict values should be
            a list as specified in the form with CSS selectors and
            props that will be applied to the specified row or column.

            .. versionchanged:: 1.2.0

        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'``). Only used if `table_styles` is
            dict.

            .. versionadded:: 1.2.0

        overwrite : bool, default True
            Styles are replaced if `True`, or extended if `False`. CSS
            rules are preserved so most recent styles set will dominate
            if selectors intersect.

            .. versionadded:: 1.2.0

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.set_td_classes: Set the DataFrame of strings added to the ``class``
            attribute of ``<td>`` HTML elements.
        Styler.set_table_attributes: Set the table attributes added to the ``<table>``
            HTML element.

        Examples
        --------
        >>> df = pd.DataFrame(np.random.randn(10, 4),
        ...                   columns=['A', 'B', 'C', 'D'])
        >>> df.style.set_table_styles(
        ...     [{'selector': 'tr:hover',
        ...       'props': [('background-color', 'yellow')]}]
        ... )

        Or with CSS strings

        >>> df.style.set_table_styles(
        ...     [{'selector': 'tr:hover',
        ...       'props': 'background-color: yellow; font-size: 1em;']}]
        ... )

        Adding column styling by name

        >>> df.style.set_table_styles({
        ...     'A': [{'selector': '',
        ...            'props': [('color', 'red')]}],
        ...     'B': [{'selector': 'td',
        ...            'props': 'color: blue;']}]
        ... }, overwrite=False)

        Adding row styling

        >>> df.style.set_table_styles({
        ...     0: [{'selector': 'td:hover',
        ...          'props': [('font-size', '25px')]}]
        ... }, axis=1, overwrite=False)
        )r   rO   z.colz.rowc               sR   g | ]J\}} |gD ]4}|D ]*}t|d    t| t|d dq qqS )ry   rL   )ry   rL   )get_indexer_forr3   r!   )rz   keyr   idxs)idfr   r+   r,   r|     s   z+Styler.set_table_styles.<locals>.<listcomp>c             S  s"   g | ]}|d  t |d dqS )ry   rL   )ry   rL   )r!   )rz   r   r+   r+   r,   r|     s   N)r   dictr4   rQ   rO   itemsr6   r   )rC   r6   r   r~   r+   )r   r   r,   r   (  s    W
zStyler.set_table_styles)r;   rE   c             C  s&   t jdtdd || _| j|| jdS )aO  
        Set the missing data representation on a ``Styler``.

        .. versionadded:: 1.0.0

        .. deprecated:: 1.3.0

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

        Returns
        -------
        self : Styler

        Notes
        -----
        This method is deprecated. See `Styler.format()`
        zAthis method is deprecated in favour of `Styler.format(na_rep=..)`r   )r   )r;   r5   )r   r   r   r;   r)   r5   )rC   r;   r+   r+   r,   
set_na_rep  s    zStyler.set_na_rep)r   rE   c             C  sL   |dkrd| _ n8t|ddf }t|}| jj| }| j|j}|| _| S )a	  
        Hide the entire index, or specific keys in the index from rendering.

        This method has dual functionality:

          - if ``subset`` is ``None`` then the entire index will be hidden whilst
            displaying all data-rows.
          - if a ``subset`` is given then those specific rows will be hidden whilst the
            index itself remains visible.

        .. versionchanged:: 1.3.0

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 1d input or single key along the index axis within
            `DataFrame.loc[<subset>, :]`, to limit ``data`` to *before* applying
            the function.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.hide_columns: Hide the entire column headers row, or specific columns.

        Examples
        --------
        Simple application hiding specific rows:

        >>> df = pd.DataFrame([[1,2], [3,4], [5,6]], index=["a", "b", "c"])
        >>> df.style.hide_index(["a", "b"])
             0    1
        c    5    6

        Hide the index and retain the data values:

        >>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
        >>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
        >>> df.style.format("{:.1f}").hide_index()
                         x                    y
           a      b      c      a      b      c
         0.1    0.0    0.4    1.3    0.6   -1.4
         0.7    1.0    1.3    1.5   -0.0   -0.2
         1.4   -0.8    1.6   -0.2   -0.4   -0.3
         0.4    1.0   -0.2   -0.8   -1.2    1.1
        -0.6    1.2    1.8    1.9    0.3    0.3
         0.8    0.5   -0.3    1.2    2.2   -0.8

        Hide specific rows but retain the index:

        >>> df.style.format("{:.1f}").hide_index(subset=(slice(None), ["a", "c"]))
                                 x                    y
                   a      b      c      a      b      c
        x   b    0.7    1.0    1.3    1.5   -0.0   -0.2
        y   b   -0.6    1.2    1.8    1.9    0.3    0.3

        Hide specific rows and the index:

        >>> df.style.format("{:.1f}").hide_index(subset=(slice(None), ["a", "c"]))
        ...     .hide_index()
                         x                    y
           a      b      c      a      b      c
         0.7    1.0    1.3    1.5   -0.0   -0.2
        -0.6    1.2    1.8    1.9    0.3    0.3
        NT)r   r   r"   r4   r   rO   r   r   )rC   r   subset_hideZhrowsr+   r+   r,   
hide_index  s    DzStyler.hide_indexc             C  sL   |dkrd| _ n8tdd|f }t|}| jj| }| j|j}|| _| S )a	  
        Hide the column headers or specific keys in the columns from rendering.

        This method has dual functionality:

          - if ``subset`` is ``None`` then the entire column headers row will be hidden
            whilst the data-values remain visible.
          - if a ``subset`` is given then those specific columns, including the
            data-values will be hidden, whilst the column headers row remains visible.

        .. versionchanged:: 1.3.0

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 1d input or single key along the columns axis within
            `DataFrame.loc[:, <subset>]`, to limit ``data`` to *before* applying
            the function.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.hide_index: Hide the entire index, or specific keys in the index.

        Examples
        --------
        Simple application hiding specific columns:

        >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])
        >>> df.style.hide_columns(["a", "b"])
             c
        0    3
        1    6

        Hide column headers and retain the data values:

        >>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
        >>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
        >>> df.style.format("{:.1f}").hide_columns()
        x   d    0.1    0.0    0.4    1.3    0.6   -1.4
            e    0.7    1.0    1.3    1.5   -0.0   -0.2
            f    1.4   -0.8    1.6   -0.2   -0.4   -0.3
        y   d    0.4    1.0   -0.2   -0.8   -1.2    1.1
            e   -0.6    1.2    1.8    1.9    0.3    0.3
            f    0.8    0.5   -0.3    1.2    2.2   -0.8

        Hide specific columns but retain the column headers:

        >>> df.style.format("{:.1f}").hide_columns(subset=(slice(None), ["a", "c"]))
                   x      y
                   b      b
        x   a    0.0    0.6
            b    1.0   -0.0
            c   -0.8   -0.4
        y   a    1.0   -1.2
            b    1.2    0.3
            c    0.5    2.2

        Hide specific columns and the column headers:

        >>> df.style.format("{:.1f}").hide_columns(subset=(slice(None), ["a", "c"]))
        ...     .hide_columns()
        x   a    0.0    0.6
            b    1.0   -0.0
            c   -0.8   -0.4
        y   a    1.0   -1.2
            b    1.2    0.3
            c    0.5    2.2
        NT)r   r   r"   r4   r   rQ   r   r   )rC   r   r   r   Zhcolsr+   r+   r,   hide_columns	  s    IzStyler.hide_columns
backgroundtextbgz${0 or 'index', 1 or 'columns', None})r   ZaltZimage_prefixr   Ztext_thresholdPuBu&1?floatzfloat | NonezSequence | None)	lowhighr   r   text_color_thresholdvminvmaxgmaprE   c
       
      C  sD   |dkr"|	dkr"| j jtjdj}| jt|||||||||	d
 | S )ap  
        Color the {name} in a gradient style.

        The {name} color is determined according
        to the data in each column, row or frame, or by a given
        gradient map. Requires matplotlib.

        Parameters
        ----------
        cmap : str or colormap
            Matplotlib colormap.
        low : float
            Compress the color range at the low end. This is a multiple of the data
            range to extend below the minimum; good values usually in [0, 1],
            defaults to 0.
        high : float
            Compress the color range at the high end. This is a multiple of the data
            range to extend above the maximum; good values usually in [0, 1],
            defaults to 0.
        axis : {axis}, 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 : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        text_color_threshold : float or int
            {text_threshold}
            Luminance threshold for determining text color in [0, 1]. Facilitates text
            visibility across varying background colors. All text is dark if 0, and
            light if 1, defaults to 0.408.
        vmin : float, optional
            Minimum data value that corresponds to colormap minimum value.
            If not specified the minimum value of the data (or gmap) will be used.

            .. versionadded:: 1.0.0

        vmax : float, optional
            Maximum data value that corresponds to colormap maximum value.
            If not specified the maximum value of the data (or gmap) will be used.

            .. versionadded:: 1.0.0

        gmap : array-like, optional
            Gradient map for determining the {name} colors. If not supplied
            will use the underlying data from rows, columns or frame. If given as an
            ndarray or list-like must be an identical shape to the underlying data
            considering ``axis`` and ``subset``. If given as DataFrame or Series must
            have same index and column labels considering ``axis`` and ``subset``.
            If supplied, ``vmin`` and ``vmax`` should be given relative to this
            gradient map.

            .. versionadded:: 1.3.0

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.{alt}_gradient: Color the {alt} in a gradient style.

        Notes
        -----
        When using ``low`` and ``high`` the range
        of the gradient, given by the data if ``gmap`` is not given or by ``gmap``,
        is extended at the low end effectively by
        `map.min - low * map.range` and at the high end by
        `map.max + high * map.range` before the colors are normalized and determined.

        If combining with ``vmin`` and ``vmax`` the `map.min`, `map.max` and
        `map.range` are replaced by values according to the values derived from
        ``vmin`` and ``vmax``.

        This method will preselect numeric columns and ignore non-numeric columns
        unless a ``gmap`` is supplied in which case no preselection occurs.

        Examples
        --------
        >>> df = pd.DataFrame(columns=["City", "Temp (c)", "Rain (mm)", "Wind (m/s)"],
        ...                   data=[["Stockholm", 21.6, 5.0, 3.2],
        ...                         ["Oslo", 22.4, 13.3, 3.1],
        ...                         ["Copenhagen", 24.5, 0.0, 6.7]])

        Shading the values column-wise, with ``axis=0``, preselecting numeric columns

        >>> df.style.{name}_gradient(axis=0)

        .. figure:: ../../_static/style/{image_prefix}_ax0.png

        Shading all values collectively using ``axis=None``

        >>> df.style.{name}_gradient(axis=None)

        .. figure:: ../../_static/style/{image_prefix}_axNone.png

        Compress the color map from the both ``low`` and ``high`` ends

        >>> df.style.{name}_gradient(axis=None, low=0.75, high=1.0)

        .. figure:: ../../_static/style/{image_prefix}_axNone_lowhigh.png

        Manually setting ``vmin`` and ``vmax`` gradient thresholds

        >>> df.style.{name}_gradient(axis=None, vmin=6.7, vmax=21.6)

        .. figure:: ../../_static/style/{image_prefix}_axNone_vminvmax.png

        Setting a ``gmap`` and applying to all columns with another ``cmap``

        >>> df.style.{name}_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd')

        .. figure:: ../../_static/style/{image_prefix}_gmap.png

        Setting the gradient map for a dataframe (i.e. ``axis=None``), we need to
        explicitly state ``subset`` to match the ``gmap`` shape

        >>> gmap = np.array([[1,2,3], [2,3,4], [3,4,5]])
        >>> df.style.{name}_gradient(axis=None, gmap=gmap,
        ...     cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)']
        ... )

        .. figure:: ../../_static/style/{image_prefix}_axNone_gmap.png
        N)include)	cmapr   r   r   r   r   r   r   r   )r4   select_dtypesr   numberrQ   r   _background_gradient)
rC   r   r   r   r   r   r   r   r   r   r+   r+   r,   background_gradientb  s     zStyler.background_gradienttgz>This argument is ignored (only used in `background_gradient`).)r   r   r   r   r   r   r   rE   c	       	      C  s@   |d kr"|d kr"| j jtjdj}| jt||||||||dd
S )N)r   T)	r   r   r   r   r   r   r   r   	text_only)r4   r  r   r  rQ   r   r  )	rC   r   r   r   r   r   r   r   r   r+   r+   r,   text_gradient  s    zStyler.text_gradientc               s.   d dd | D  | j fdd|dS )a  
        Set defined CSS-properties to each ``<td>`` HTML element within the given
        subset.

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        **kwargs : dict
            A dictionary of property, value pairs to be set for each cell.

        Returns
        -------
        self : Styler

        Notes
        -----
        This is a convenience methods which wraps the :meth:`Styler.applymap` calling a
        function returning the CSS-properties independently of the data.

        Examples
        --------
        >>> df = pd.DataFrame(np.random.randn(10, 4))
        >>> df.style.set_properties(color="white", align="right")
        >>> df.style.set_properties(**{'background-color': 'yellow'})
        rY   c             s  s"   | ]\}}| d | dV  qdS )z: ;Nr+   )rz   pvr+   r+   r,   r   C  s    z(Styler.set_properties.<locals>.<genexpr>c               s    S )Nr+   )x)valuesr+   r,   r   D  r   z'Styler.set_properties.<locals>.<lambda>)r   )joinr   r   )rC   r   rJ   r+   )r  r,   set_properties&  s    zStyler.set_propertiesd   z	list[str])alignr#   widthr   r   c       	        s  |dkrt |  n|}|dkr0t |  n|} dkrRtd|}td|}n  dkrrtt|t|}| }| jtd|  || d  } | || d  ddddd	fd
d fdd| jdkrfdd|D S t	fdd|D | j
| jdS dS )z4
        Draw bar chart in dataframe cells.
        Nmidr   zero)dtypeg-q=r   r3   )startendcolorrE   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%,  z%, transparent z%))min)r  r  r  csse)r  r+   r,   css_bar`  s     
zStyler._bar.<locals>.css_barc               sV   t | rdS | krd nd } dkr:d| |S t| t| |S d S )NrY   r   r   left)r   r   r  max)r  r  )r  r#   r  r  r+   r,   r  m  s    
zStyler._bar.<locals>.cssr   c               s   g | ]} |qS r+   r+   )rz   r  )r  r+   r,   r|   z  s    zStyler._bar.<locals>.<listcomp>c               s   g | ]} fd d|D qS )c               s   g | ]} |qS r+   r+   )rz   r  )r  r+   r,   r|   }  s    z*Styler._bar.<locals>.<listcomp>.<listcomp>r+   )rz   row)r  r+   r,   r|   }  s    )rO   rQ   )r   nanminto_numpynanmaxr  r  absr   ndimr   rO   rQ   )	r   r  r#   r  r   r   sminsmaxnormedr+   )r  r#   r  r  r  r  r,   _barF  s$    
 
zStyler._bar#d65f5fr  )r   r   r  r  r   r   rE   c          
   C  s   |dkrt dt|s"||g}n2t|dkr@|d |d g}nt|dkrTt d|dkrn| jjtjdj}| j| j	|||||||d	 | S )
a  
        Draw bar chart in the cell backgrounds.

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        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.
        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.

        Returns
        -------
        self : Styler
        )r  r  r  z.`align` must be one of {'left', 'zero',' mid'}r   r   r   zp`color` must be string or a list-like of length 2: [`color_neg`, `color_pos`] (eg: color=['#d65f5f', '#5fba7d'])N)r   )r   r   r  r#   r  r   r   )
r   r   r   r4   r  r   r  rQ   r   r(  )rC   r   r   r  r  r  r   r   r+   r+   r,   bar  s*    4
z
Styler.barred)
null_colorr   rL   rE   c             C  s8   dddddd}|dkr&d| d	}| j |d||d
S )a  
        Highlight missing values with a style.

        Parameters
        ----------
        null_color : str, default 'red'
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.

            .. versionadded:: 1.1.0

        props : str, default None
            CSS properties to use for highlighting. If ``props`` is given, ``color``
            is not used.

            .. versionadded:: 1.3.0

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.highlight_max: Highlight the maximum with a style.
        Styler.highlight_min: Highlight the minimum with a style.
        Styler.highlight_between: Highlight a defined range with a style.
        Styler.highlight_quantile: Highlight values defined by a quantile with a style.
        r   r3   z
np.ndarray)r4   rL   rE   c             S  s   t t|  |dS )NrY   )r   r   r   r   r!  )r4   rL   r+   r+   r,   f  s    z Styler.highlight_null.<locals>.fNzbackground-color: r  )r   r   rL   )r   )rC   r,  r   rL   r-  r+   r+   r,   highlight_null  s
    %zStyler.highlight_nullyellow)r   r  r   rL   rE   c             C  s.   |dkrd| d}| j ttdd|||dS )a  
        Highlight the maximum with a style.

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        color : str, default 'yellow'
            Background color to use for highlighting.
        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``.
        props : str, default None
            CSS properties to use for highlighting. If ``props`` is given, ``color``
            is not used.

            .. versionadded:: 1.3.0

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.highlight_null: Highlight missing values with a style.
        Styler.highlight_min: Highlight the minimum with a style.
        Styler.highlight_between: Highlight a defined range with a style.
        Styler.highlight_quantile: Highlight values defined by a quantile with a style.
        Nzbackground-color: r  r  )op)r   r   rL   )r   r   _highlight_value)rC   r   r  r   rL   r+   r+   r,   highlight_max	  s    (
zStyler.highlight_maxc             C  s.   |dkrd| d}| j ttdd|||dS )a  
        Highlight the minimum with a style.

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        color : str, default 'yellow'
            Background color to use for highlighting.
        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``.
        props : str, default None
            CSS properties to use for highlighting. If ``props`` is given, ``color``
            is not used.

            .. versionadded:: 1.3.0

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.highlight_null: Highlight missing values with a style.
        Styler.highlight_max: Highlight the maximum with a style.
        Styler.highlight_between: Highlight a defined range with a style.
        Styler.highlight_quantile: Highlight values defined by a quantile with a style.
        Nzbackground-color: r  r  )r0  )r   r   rL   )r   r   r1  )rC   r   r  r   rL   r+   r+   r,   highlight_min7	  s    (
zStyler.highlight_minbothzScalar | Sequence | None)r   r  r   r  right	inclusiverL   rE   c          	   C  s,   |dkrd| d}| j t||||||dS )a  
        Highlight a defined range with a style.

        .. versionadded:: 1.3.0

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        color : str, default 'yellow'
            Background color to use for highlighting.
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            If ``left`` or ``right`` given as sequence, axis along which to apply those
            boundaries. See examples.
        left : scalar or datetime-like, or sequence or array-like, default None
            Left bound for defining the range.
        right : scalar or datetime-like, or sequence or array-like, default None
            Right bound for defining the range.
        inclusive : {'both', 'neither', 'left', 'right'}
            Identify whether bounds are closed or open.
        props : str, default None
            CSS properties to use for highlighting. If ``props`` is given, ``color``
            is not used.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.highlight_null: Highlight missing values with a style.
        Styler.highlight_max: Highlight the maximum with a style.
        Styler.highlight_min: Highlight the minimum with a style.
        Styler.highlight_quantile: Highlight values defined by a quantile with a style.

        Notes
        -----
        If ``left`` is ``None`` only the right bound is applied.
        If ``right`` is ``None`` only the left bound is applied. If both are ``None``
        all values are highlighted.

        ``axis`` is only needed if ``left`` or ``right`` are provided as a sequence or
        an array-like object for aligning the shapes. If ``left`` and ``right`` are
        both scalars then all ``axis`` inputs will give the same result.

        This function only works with compatible ``dtypes``. For example a datetime-like
        region can only use equivalent datetime-like ``left`` and ``right`` arguments.
        Use ``subset`` to control regions which have multiple ``dtypes``.

        Examples
        --------
        Basic usage

        >>> df = pd.DataFrame({
        ...     'One': [1.2, 1.6, 1.5],
        ...     'Two': [2.9, 2.1, 2.5],
        ...     'Three': [3.1, 3.2, 3.8],
        ... })
        >>> df.style.highlight_between(left=2.1, right=2.9)

        .. figure:: ../../_static/style/hbetw_basic.png

        Using a range input sequnce along an ``axis``, in this case setting a ``left``
        and ``right`` for each column individually

        >>> df.style.highlight_between(left=[1.4, 2.4, 3.4], right=[1.6, 2.6, 3.6],
        ...     axis=1, color="#fffd75")

        .. figure:: ../../_static/style/hbetw_seq.png

        Using ``axis=None`` and providing the ``left`` argument as an array that
        matches the input DataFrame, with a constant ``right``

        >>> df.style.highlight_between(left=[[2,2,3],[2,2,3],[3,3,3]], right=3.5,
        ...     axis=None, color="#fffd75")

        .. figure:: ../../_static/style/hbetw_axNone.png

        Using ``props`` instead of default background coloring

        >>> df.style.highlight_between(left=1.5, right=3.5,
        ...     props='font-weight:bold;color:#e83e8c')

        .. figure:: ../../_static/style/hbetw_props.png
        Nzbackground-color: r  )r   r   rL   r  r5  r6  )r   _highlight_between)rC   r   r  r   r  r5  r6  rL   r+   r+   r,   highlight_betweenj	  s    azStyler.highlight_between              ?linear)	r   r  r   q_leftq_rightinterpolationr6  rL   rE   c	          	   C  s   |dkrt dn|}	t|	}	| jj|	 }
||g|d}|dkrZ|
jf |dd|}d}n@|dkr~|
jf |dd|}d}nt|
  jf |}d}|dkrd	| d
}| jt	||||j
d |j
d |dS )uh
  
        Highlight values defined by a quantile with a style.

        .. versionadded:: 1.3.0

        Parameters
        ----------
        subset : label, array-like, IndexSlice, optional
            A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
            or single key, to `DataFrame.loc[:, <subset>]` where the columns are
            prioritised, to limit ``data`` to *before* applying the function.
        color : str, default 'yellow'
            Background color to use for highlighting
        axis : {0 or 'index', 1 or 'columns', None}, default 0
            Axis along which to determine and highlight quantiles. If ``None`` quantiles
            are measured over the entire DataFrame. See examples.
        q_left : float, default 0
            Left bound, in [0, q_right), for the target quantile range.
        q_right : float, default 1
            Right bound, in (q_left, 1], for the target quantile range.
        interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}
            Argument passed to ``Series.quantile`` or ``DataFrame.quantile`` for
            quantile estimation.
        inclusive : {'both', 'neither', 'left', 'right'}
            Identify whether quantile bounds are closed or open.
        props : str, default None
            CSS properties to use for highlighting. If ``props`` is given, ``color``
            is not used.

        Returns
        -------
        self : Styler

        See Also
        --------
        Styler.highlight_null: Highlight missing values with a style.
        Styler.highlight_max: Highlight the maximum with a style.
        Styler.highlight_min: Highlight the minimum with a style.
        Styler.highlight_between: Highlight a defined range with a style.

        Notes
        -----
        This function does not work with ``str`` dtypes.

        Examples
        --------
        Using ``axis=None`` and apply a quantile to all collective data

        >>> df = pd.DataFrame(np.arange(10).reshape(2,5) + 1)
        >>> df.style.highlight_quantile(axis=None, q_left=0.8, color="#fffd75")

        .. figure:: ../../_static/style/hq_axNone.png

        Or highlight quantiles row-wise or column-wise, in this case by row-wise

        >>> df.style.highlight_quantile(axis=1, q_left=0.8, color="#fffd75")

        .. figure:: ../../_static/style/hq_ax1.png

        Use ``props`` instead of default background coloring

        >>> df.style.highlight_quantile(axis=None, q_left=0.2, q_right=0.8,
        ...     props='font-weight:bold;color:#e83e8c')

        .. figure:: ../../_static/style/hq_props.png
        N)qr>  )r   rO   F)r   Znumeric_onlyr   )r   rQ   r   zbackground-color: r  )r   r   rL   r  r5  r6  )r   r"   r4   r   Zquantiler   r!  Zravelr   r7  Ziloc)rC   r   r  r   r<  r=  r>  r6  rL   r   r4   rJ   r?  Z
axis_applyr+   r+   r,   highlight_quantile	  s,    MzStyler.highlight_quantile)
html_table
html_stylec               s2   t t || jgG  fddd| }|S )a  
        Factory function for creating a subclass of ``Styler``.

        Uses custom templates and Jinja environment.

        .. versionchanged:: 1.3.0

        Parameters
        ----------
        searchpath : str or list
            Path or paths of directories containing the templates.
        html_table : str
            Name of your custom template to replace the html_table template.

            .. versionadded:: 1.3.0

        html_style : str
            Name of your custom template to replace the html_style template.

            .. versionadded:: 1.3.0

        Returns
        -------
        MyStyler : subclass of Styler
            Has the correct ``env``,``template_html``, ``template_html_table`` and
            ``template_html_style`` class attributes set.
        c                  s4   e Zd ZejdZr"eZ r0e ZdS )z-Styler.from_custom_template.<locals>.MyStyler)loaderN)	r*   
__module____qualname__r   EnvironmentenvZget_templateZtemplate_html_tableZtemplate_html_styler+   )rB  rA  rC  r+   r,   MyStylere
  s
   
rH  )r   ZChoiceLoaderZFileSystemLoaderrC  )clsZ
searchpathrA  rB  rH  r+   )rB  rA  rC  r,   from_custom_templateA
  s    zStyler.from_custom_template)r$   c             O  s   t j| |f||S )a=	  
        Apply ``func(self, *args, **kwargs)``, and return the result.

        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 CSS-styling function column-wise, row-wise, or
            table-wise.

        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."))
        )compipe)rC   r$   argsrJ   r+   r+   r,   rL  n
  s    CzStyler.pipe)NNNNNTNr/   r0   NN)NN)NN)rX   rY   NNTTNr   r   NTNrZ   TN)N)N)F)r   N)r   N)N)N)NN)r   NN)r   T)N)N)	r   r   r   r   Nr   NNN)r   r   r   r   NNNN)N)r  NN)Nr   r)  r  r  NN)r+  NN)Nr/  r   N)Nr/  r   N)Nr/  r   NNr4  N)Nr/  r   r9  r:  r;  r4  N)NN)4r*   rD  rE  __doc__rB   rG   rF   rU   r   r   rk   r   Z_shared_docsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  staticmethodr(  r*  r.  r2  r3  r8  r@  classmethodrJ  rL  __classcell__r+   r+   )rD   r,   r.   O   s>  ^          * 8 [              0.  q<L6 , I: G    qPY        "            7      L  .   0   0      g        a+r.   z%FrameOrSeries | Sequence | np.ndarrayr3   z
Any | Noner   z
np.ndarray)argarg_namer  r4   rE   c             C  s   |rd|ini }t | tr6t |tr6td| dnt | tr\t |tr\td| dnnt | ttfr| j|ddjf |} nHtj| f|} t | tjst	| j
|j
krtd| d| j
 d	|j
 | S )
a  
    For the apply-type methods, ``axis=None`` creates ``data`` as DataFrame, and for
    ``axis=[1,0]`` it creates a Series. Where ``arg`` is expected as an element
    of some operator with ``data`` we must make sure that the two are compatible shapes,
    or raise.

    Parameters
    ----------
    arg : sequence, Series or DataFrame
        the user input arg
    arg_name : string
        name of the arg for use in error messages
    dtype : numpy dtype, optional
        forced numpy dtype if given
    data : Series or DataFrame
        underling subset of Styler data on which operations are performed

    Returns
    -------
    ndarray
    r  r   zQ' is a Series but underlying data for operations is a DataFrame since 'axis=None'zT' is a DataFrame but underlying data for operations is a Series with 'axis in [0,1]'N)methodz
supplied 'z:' is not correct shape for data over selected 'axis': got z, expected )r   r   r   r   r   r!  r   Zasarrayr   AssertionErrorr   )rR  rS  r  r4   r+   r+   r,   _validate_apply_axis_arg
  s    rV  r   &1?r   zfloat | Nonez,Sequence | np.ndarray | FrameOrSeries | Noner1   )r   r   r   r   r   r   r  c	          	     s
  |dkr| j td}nt|dt| }ttj\}	 |dkrFt|n|}
|dkr\t|n|}||
 } 	|
||  |||  }|	j
|||}dddddd fd	d
| jdkrڇfdd|D S tfdd|D | j| jdS W dQ R X dS )zM
    Color background in a range according to the data or a gradient map
    N)r  r   r   )rE   c             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 d V  qdS )g?ܵ?gףp=
)@g)\(?gzG?g333333@Nr+   )rz   r  r+   r+   r,   r     s   zC_background_gradient.<locals>.relative_luminance.<locals>.<genexpr>N   gz6?g,C?g]m{?r+   )rgbarm   gbr+   r+   r,   relative_luminance  s    z0_background_gradient.<locals>.relative_luminancer3   c               sJ   |s4| k }|rdnd}d  |  d| dS d  |  dS d S )Nz#f1f1f1z#000000zbackground-color: z;color: r  zcolor: )Zrgb2hex)rY  r  ZdarkZ
text_color)r#   r\  r   r+   r,   r    s
    z!_background_gradient.<locals>.cssr   c               s   g | ]} |qS r+   r+   )rz   rY  )r  r  r+   r,   r|   #  s    z(_background_gradient.<locals>.<listcomp>c               s    g | ]} fd d|D qS )c               s   g | ]} |qS r+   r+   )rz   rY  )r  r  r+   r,   r|   &  s    z3_background_gradient.<locals>.<listcomp>.<listcomp>r+   )rz   r  )r  r  r+   r,   r|   &  s    )rO   rQ   )r!  r   rV  r-   r.   r  r   r   r"  Z	NormalizecmZget_cmapr$  r   rO   rQ   )r4   r   r   r   r   r   r   r   r  r&   r%  r&  rngZnormZrgbasr+   )r#   r  r\  r   r  r,   r  
  s"    
r  z5Scalar | Sequence | np.ndarray | FrameOrSeries | Nonez
bool | str)r4   rL   r  r5  r6  rE   c             C  s  t |r"t|ts"t|dd| }t |rDt|tsDt|dd| }|dkrZtjtjf}nP|dkrptjtj	f}n:|dkrtjtj	f}n$|dkrtjtjf}nt
d| |dk	r|d | |nt j| jdtd	}|dk	r|d
 | |nt j| jdtd	}t ||@ |dS )z\
    Return an array of css props based on condition of data values within given range.
    r  Nr5  r4  ZneitherzD'inclusive' values can be 'both', 'left', 'right', or 'neither' got r   T)r  r   rY   )r   iterabler   r3   rV  operatorgelegtltr   fullr   r1   r   )r4   rL   r  r5  r6  ZopsZg_leftZl_rightr+   r+   r,   r7  ,  s*    
r7  )r4   r0  rL   rE   c             C  s<   t | |dd}t| tr*t ||dd}t| |k|dS )zY
    Return an array of css strings based on the condition of values matching an op.
    T)ZskipnarY   )r   r   r   r   r   )r4   r0  rL   r   r+   r+   r,   r1  \  s    
r1  )r   r   r   rW  NNNF)NNT)HrN  
__future__r   
contextlibr   r   	functoolsr   r`  typingr   r   r   r   r   numpyr   Zpandas._configr	   Zpandas._typingr
   r   r   r   r   r   Zpandas.compat._optionalr   Zpandas.util._decoratorsr   Zpandasr   r   r   Zpandas.api.typesr   Zpandas.corer   Zpandas.core.commoncorecommonrK  Zpandas.core.framer   r   Zpandas.core.genericr   Zpandas.io.formats.formatr   r   Zpandas.io.formats.style_renderr   r   r   r   r    r!   r"   Z
matplotlibr#   Zmatplotlib.pyplotZpyplotr&   r%   r'   r(   r-   r.   rV  r  r7  r1  r+   r+   r+   r,   <module>   s    $

                    y7       =  +