gL i`dZddlmZddlmZddlZddlmZddlZddl m Z m Z m Z m Z ddlZddlZddlmZddlmZdd lmZmZdd lmZddlZdd lmZmZddlmcm Z!dd l"m#Z#m$Z$dd l%m&Z&ddl'm(Z(ddl)m*Z*eddZ+ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6e r0ddl7m8Z8m9Z9m:Z:ddl;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHddlmIZI ddlJZKddlLmMZNdZOed'dZQdZRdZSdZTdZUdZVGd d!e0ZW d(d"ZX d) d*d#ZY d+ d,d$ZZd-d%Z[ d.d&Z\y#eP$rdZOYwxYw)/zF Module for applying conditional formatting to DataFrames and Series. ) annotations)contextmanagerN)partial) TYPE_CHECKINGAnyCallableoverload) get_option)import_optional_dependency) Substitutiondoc)find_stack_level) IndexSlice RangeIndex) DataFrameSeries)NDFrame) _shared_docs)save_to_bufferjinja2z DataFrame.style requires jinja2.)extra) CSSProperties CSSStyles ExtFormatterStylerRendererSubsetTooltipsformat_table_stylesmaybe_convert_css_to_tuplesnon_reducing_slicerefactor_levels) GeneratorHashableSequence)Colormap) AxisAxisIntFilePath IndexLabelIntervalClosedTypeLevelQuantileInterpolationScalarStorageOptions WriteBufferWriteExcelBuffer) ExcelWriterTFc#dKtrttfyt|jdw)Nz requires matplotlib.)has_mplpltmpl ImportError__name__)funcs ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/pandas/io/formats/style.py_mplr:]s)3hT]]O+@ABBs.0a(subset : label, array-like, IndexSlice, optional A valid 2d input to `DataFrame.loc[]`, or, in the case of a 1d input or single key, to `DataFrame.loc[:, ]` where the columns are prioritised, to limit ``data`` to *before* applying the function.zprops : str, default None CSS properties to use for highlighting. If ``props`` is given, ``color`` is not used.zUcolor : str, default '{default}' Background color to use for highlighting.zbuf : str, path object, file-like object, optional String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``write()`` function. If ``None``, the result is returned as a string.zencoding : str, optional Character encoding setting for file output (and meta tags if available). Defaults to ``pandas.options.styler.render.encoding`` value of "utf-8".c eZdZdZ db dcfd ZdddZdedZdedZ df dgdZe e jde dd  dh did Z e d d d d d d d d d d d d d d d d djdZe dkd d d d d d d d d d d d d d d d dldZ dmdddddddddddddddd dndZe d d d d d d d d d d d d dodZe dkd d d d d d d d d d d d dpdZeee dmdddddddddddd dqdZe d d d d d d d drdZe dkd d d d d d d dsdZeee dmddddddd dtdZdudZdvdZdwdZdxdyd Zdzd!Zdzd"Zd{d#Z d| d}d$Zee% d| d}d&Z d~ dd(Ze d'd)d*d+d,d-d.d/d0d12 d| dd3Ze ed*d+d'd)d4d5d6d7d8d92 d| dd:Z d| dd;Z!dmdd<Z"ee%dmdd=Z#ee% dm dd>Z$dd?Z%dd@Z&ddAZ'ddBZ(ddCZ) d ddDZ* d ddEZ+ d ddFZ,dGZ-e dHdIdJdKLee% d ddMZ.e e.dIdHdNd L d ddOZ/ee%dmddPZ0ee% ddddQdQdRdddSdT ddUZ1eee2e3jidVWX d ddYZ5eee3jidZWe2[ d dd\Z6eee3jidZWe2[ d dd]Z7eee3jidZWe2[ d dd^Z8eee3jidZWe2[ d dd_Z9e: df dd`Z;ddaZ<xZ=S)Stylera Helps style a DataFrame or Series according to the data with HTML and CSS. Parameters ---------- data : Series or DataFrame Data to be styled - either a Series or DataFrame. precision : int, optional Precision to round floats to. If not given defaults to ``pandas.options.styler.format.precision``. .. versionchanged:: 1.4.0 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 ```` 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__row_col`` where ```` is the unique identifier, ```` is the row number and ```` is the column number. na_rep : str, optional Representation for missing values. If ``na_rep`` is None, no special formatting is applied, and falls back to ``pandas.options.styler.format.na_rep``. 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]. decimal : str, optional Character used as decimal separator for floats, complex and integers. If not given uses ``pandas.options.styler.format.decimal``. .. versionadded:: 1.3.0 thousands : str, optional, default None Character used as thousands separator for floats, complex and integers. If not given uses ``pandas.options.styler.format.thousands``. .. 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. Use 'latex-math' to replace the characters the same way as in 'latex' mode, except for math substrings, which either are surrounded by two characters ``$`` or start with the character ``\(`` and end with ``\)``. If not given uses ``pandas.options.styler.format.escape``. .. versionadded:: 1.3.0 formatter : str, callable, dict, optional Object to define how values are displayed. See ``Styler.format``. If not given uses ``pandas.options.styler.format.formatter``. .. versionadded:: 1.4.0 Attributes ---------- env : Jinja2 jinja2.Environment template_html : Jinja2 Template template_html_table : Jinja2 Template template_html_style : Jinja2 Template template_latex : 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.map``. 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.to_html to get the generated HTML. CSS classes are attached to the generated HTML * Index and Column names include ``index_name`` and ``level`` where `k` is its level in a MultiIndex * Index label cells include * ``row_heading`` * ``row`` where `n` is the numeric position of the row * ``level`` where `k` is the level in a MultiIndex * Column label cells include * ``col_heading`` * ``col`` where `n` is the numeric position of the column * ``level`` where `k` is the level in a MultiIndex * Blank cells include ``blank`` * Data cells include ``data`` * Trimmed cells include ``col_trim`` or ``row_trim``. Any, or all, or these classes can be renamed by using the ``css_class_names`` argument in ``Styler.set_table_classes``, giving a value such as *{"row": "MY_ROW_CLASS", "col_trim": "", "row_trim": ""}*. Examples -------- >>> df = pd.DataFrame([[1.0, 2.0, 3.0], [4, 5, 6]], index=['a', 'b'], ... columns=['A', 'B', 'C']) >>> pd.io.formats.style.Styler(df, precision=2, ... caption="My table") # doctest: +SKIP Please see: `Table Visualization <../../user_guide/style.ipynb>`_ for more examples. Nc t|||| |||||| xs td} | xs td} |xs td}| xs td} | xs td} |j| ||| | | y)N)datauuiduuid_len table_stylestable_attributescaptioncell_ids precisionzstyler.format.thousandszstyler.format.decimalzstyler.format.na_repzstyler.format.escapezstyler.format.formatter) formatterrEna_repescapedecimal thousands)super__init__r format)selfr>rErAr?rCrBrDrGr@rIrJrHrF __class__s r9rLzStyler.__init__s %-  F,E!F @Z(?@=:&<==:&<=F,E!F    ct|ts td|jjj |jjs t d|jjj|jjjk(s t d|jj||S)a Append another Styler to combine the output into a single table. .. versionadded:: 1.5.0 Parameters ---------- other : Styler The other Styler object which has already been styled and formatted. The data for this Styler must have the same columns as the original, and the number of index levels must also be the same to render correctly. Returns ------- Styler Notes ----- The purpose of this method is to extend existing styled dataframes with other metrics that may be useful but may not conform to the original's structure. For example adding a sub total row, or displaying metrics such as means, variance or counts. Styles that are applied using the ``apply``, ``map``, ``apply_index`` and ``map_index``, and formatting applied with ``format`` and ``format_index`` will be preserved. .. warning:: Only the output methods ``to_html``, ``to_string`` and ``to_latex`` currently work with concatenated Stylers. Other output methods, including ``to_excel``, **do not** work with concatenated Stylers. The following should be noted: - ``table_styles``, ``table_attributes``, ``caption`` and ``uuid`` are all inherited from the original Styler and not ``other``. - hidden columns and hidden index levels will be inherited from the original Styler - ``css`` will be inherited from the original Styler, and the value of keys ``data``, ``row_heading`` and ``row`` will be prepended with ``foot0_``. If more concats are chained, their styles will be prepended with ``foot1_``, ''foot_2'', etc., and if a concatenated style have another concatanated style, the second style will be prepended with ``foot{parent}_foot{child}_``. A common use case is to concatenate user defined functions with ``DataFrame.agg`` or with described statistics via ``DataFrame.describe``. See examples. Examples -------- A common use case is adding totals rows, or otherwise, via methods calculated in ``DataFrame.agg``. >>> df = pd.DataFrame([[4, 6], [1, 9], [3, 4], [5, 5], [9, 6]], ... columns=["Mike", "Jim"], ... index=["Mon", "Tue", "Wed", "Thurs", "Fri"]) >>> styler = df.style.concat(df.agg(["sum"]).style) # doctest: +SKIP .. figure:: ../../_static/style/footer_simple.png Since the concatenated object is a Styler the existing functionality can be used to conditionally format it as well as the original. >>> descriptors = df.agg(["sum", "mean", lambda s: s.dtype]) >>> descriptors.index = ["Total", "Average", "dtype"] >>> other = (descriptors.style ... .highlight_max(axis=1, subset=(["Total", "Average"], slice(None))) ... .format(subset=("Average", slice(None)), precision=2, decimal=",") ... .map(lambda v: "font-weight: bold;")) >>> styler = (df.style ... .highlight_max(color="salmon") ... .set_table_styles([{"selector": ".foot_row0", ... "props": "border-top: 1px solid black;"}])) >>> styler.concat(other) # doctest: +SKIP .. figure:: ../../_static/style/footer_extended.png When ``other`` has fewer index levels than the original Styler it is possible to extend the index in ``other``, with placeholder levels. >>> df = pd.DataFrame([[1], [2]], ... index=pd.MultiIndex.from_product([[0], [1, 2]])) >>> descriptors = df.agg(["sum"]) >>> descriptors.index = pd.MultiIndex.from_product([[""], descriptors.index]) >>> df.style.concat(descriptors.style) # doctest: +SKIP z `other` must be of type `Styler`z4`other.data` must have same columns as `Styler.data`zanumber of index levels must be same in `other` as in `Styler`. See documentation for suggestions.) isinstancer< TypeErrorr>columnsequals ValueErrorindexnlevels concatenatedappend)rNothers r9concatz Styler.concat)st%(>? ?yy  '' (:(:;ST Tyy&&%***:*:*B*BBE    ' rPc@tddk(r|jSy)z Hooks into Jupyter notebook rich display system, which calls _repr_html_ by default if an object is returned at the end of a cell. styler.render.reprhtmlN)r to_htmlrNs r9 _repr_html_zStyler._repr_html_s! * +v 5<<> !rPc@tddk(r|jSy)Nr^latex)r to_latexras r9 _repr_latex_zStyler._repr_latex_s * +w 6==? "rPcF|js td|jjr|jjs t d|j t|_||j _|r||j _ |r||j _ |S)a Set the DataFrame of strings on ``Styler`` generating ``:hover`` tooltips. These string based tooltips are only applicable to ``
`` 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 ------- Styler Notes ----- Tooltips are created by adding `` 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).to_html() Optionally controlling the tooltip visual display >>> df.style.set_tooltips(ttips, css_class='tt-add', props=[ ... ('visibility', 'hidden'), ... ('position', 'absolute'), ... ('z-index', 1)]) # doctest: +SKIP >>> df.style.set_tooltips(ttips, css_class='tt-add', ... props='visibility:hidden; position:absolute; z-index:1;') ... # doctest: +SKIP z1Tooltips can only render with 'cell_ids' is True.z=Tooltips render only if `ttips` has unique index and columns.) rDNotImplementedErrorrW is_uniquerTKeyErrortooltipsrtt_dataclass_properties class_name)rNttipsprops css_classs r9 set_tooltipszStyler.set_tooltipssX}}&C {{$$EMM,C,CO  == $JDM %  -2DMM * '0DMM $ rPstorage_optionsz1.5.0)klassrsstorage_options_versionaddedc bddlm}||||||||| | }|j||| | || |y)Nr)ExcelFormatter)rGcolsheader float_formatrW index_label merge_cellsinf_rep) sheet_namestartrowstartcol freeze_panesenginers)pandas.io.formats.excelrxwrite)rN excel_writerrrGr{rTrzrWr|rrrr}encodingr~verboserrsrxrFs r9to_excelzStyler.to_excelsT4 ;" %##    !%+  rP.) column_formatpositionposition_floathrulesclineslabelrC sparse_indexsparse_columnsmultirow_alignmulticol_alignsiunitx environmentr convert_csscyNrNbufrrrrrrrCrrrrrrrrs r9rezStyler.to_latex.* rPcyrrrs r9rezStyler.to_latexErrPFc |jd}|j|jDcgc]}|d c}ng}||jdd|dgdn2d|vrn,|jj}t t |jj |j_|jjjj}||j_d }t|jjD]}||j|rd nd z }t|jjD]#\}}||jvs|||vr| sd nd nd z }%|jdd|dgd|r|jdd|dgd|r=|dk(r td|dvrtd|d|jdd|dgd| t!dn|}|r|jdddddddddgd|r+|jdd|j#ddddgd|r|j%|| t!d } | t!d!} |xs t!d"}| xs t!d#} | xs t!d$} |j'| | | | ||| |%}t)|t*r|xs t!d&n|}t-|||'Scc}w)(u;V Write Styler to a file, buffer or string in LaTeX format. .. versionadded:: 1.3.0 Parameters ---------- buf : str, path object, file-like object, or None, default None String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``write()`` function. If None, the result is returned as a string. column_format : str, optional The LaTeX column specification placed in location: \\begin{tabular}{} 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_float : {"centering", "raggedleft", "raggedright"}, optional The LaTeX float command placed in location: \\begin{table}[] \\ Cannot be used if ``environment`` is "longtable". hrules : bool Set to `True` to add \\toprule, \\midrule and \\bottomrule from the {booktabs} LaTeX package. Defaults to ``pandas.options.styler.latex.hrules``, which is `False`. .. versionchanged:: 1.4.0 clines : str, optional Use to control adding \\cline commands for the index labels separation. Possible values are: - `None`: no cline commands are added (default). - `"all;data"`: a cline is added for every index value extending the width of the table, including data entries. - `"all;index"`: as above with lines extending only the width of the index entries. - `"skip-last;data"`: a cline is added for each index value except the last level (which is never sparsified), extending the widtn of the table. - `"skip-last;index"`: as above with lines extending only the width of the index entries. .. versionadded:: 1.4.0 label : str, optional The LaTeX label included as: \\label{
}. If tuple, i.e ("full caption", "short caption"), the caption included as: \\caption[]{}. 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``, which is `True`. 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 column. Defaults to ``pandas.options.styler.sparse.columns``, which is `True`. multirow_align : {"c", "t", "b", "naive"}, optional If sparsifying hierarchical MultiIndexes whether to align text centrally, at the top or bottom using the multirow package. If not given defaults to ``pandas.options.styler.latex.multirow_align``, which is `"c"`. If "naive" is given renders without multirow. .. versionchanged:: 1.4.0 multicol_align : {"r", "c", "l", "naive-l", "naive-r"}, optional If sparsifying hierarchical MultiIndex columns whether to align text at the left, centrally, or at the right. If not given defaults to ``pandas.options.styler.latex.multicol_align``, which is "r". If a naive option is given renders without multicol. Pipe decorators can also be added to non-naive values to draw vertical rules, e.g. "\|r" will draw a rule on the left side of right aligned merged cells. .. versionchanged:: 1.4.0 siunitx : bool, default False Set to ``True`` to structure LaTeX compatible with the {siunitx} package. environment : str, optional If given, the environment that will replace 'table' in ``\\begin{table}``. If 'longtable' is specified then a more suitable template is rendered. If not given defaults to ``pandas.options.styler.latex.environment``, which is `None`. .. versionadded:: 1.4.0 encoding : str, optional Character encoding setting. Defaults to ``pandas.options.styler.render.encoding``, which is "utf-8". 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})* environment \\usepackage{longtable} if arg is "longtable" | or any other relevant environment package hyperlinks \\usepackage{hyperref} ===================== ========================================================== **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 ``(, )`` pair (see `Table Visualization <../../user_guide/style.ipynb>`_), and this should be replaced by a LaTeX ``(, )`` 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.to_html() # doctest: +SKIP The equivalent using LaTeX only commands is the following: >>> s = df.style.highlight_max(axis=None, ... props='cellcolor:{red}; bfseries: ;') >>> s.to_latex() # doctest: +SKIP Internally these structured LaTeX ``(, )`` pairs are translated to the ``display_value`` with the default structure: ``\ ``. Where there are multiple commands the latter is nested recursively, so that the above example highlighted 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 ````, within the tuple, to result in different positions of required braces (the **default** being the same as ``--nowrap``): =================================== ============================================ Tuple Format Output Structure =================================== ============================================ (,) \\ (, ``--nowrap``) \\ (, ``--rwrap``) \\{} (, ``--wrap``) {\\ } (, ``--lwrap``) {\\} (, ``--dwrap``) {\\}{} =================================== ============================================ 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{}``. 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() # doctest: +SKIP .. 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" ... ) # doctest: +SKIP .. 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` for example: >>> s.clear() >>> s.table_styles = [] >>> s.caption = None >>> s.format({ ... ("Numeric", "Integers"): '\${}', ... ("Numeric", "Floats"): '{:.3f}', ... ("Non-Numeric", "Strings"): str.upper ... }) # doctest: +SKIP Numeric Non-Numeric Integers Floats Strings L0 ix1 $1 2.200 DOGS ix2 $3 4.400 CATS L1 ix3 $2 6.600 COWS >>> s.to_latex() # doctest: +SKIP \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) # doctest: +SKIP \begin{tabular}{lr} {} & {0} \\ 0 & {\bfseries}{\Huge{1}} \\ \end{tabular} Examples -------- Below we give a complete step by step example adding some advanced features and noting some common gotchas. First we create the DataFrame and Styler as usual, including MultiIndex rows and columns, which allow for more advanced formatting options: >>> cidx = pd.MultiIndex.from_arrays([ ... ["Equity", "Equity", "Equity", "Equity", ... "Stats", "Stats", "Stats", "Stats", "Rating"], ... ["Energy", "Energy", "Consumer", "Consumer", "", "", "", "", ""], ... ["BP", "Shell", "H&M", "Unilever", ... "Std Dev", "Variance", "52w High", "52w Low", ""] ... ]) >>> iidx = pd.MultiIndex.from_arrays([ ... ["Equity", "Equity", "Equity", "Equity"], ... ["Energy", "Energy", "Consumer", "Consumer"], ... ["BP", "Shell", "H&M", "Unilever"] ... ]) >>> styler = pd.DataFrame([ ... [1, 0.8, 0.66, 0.72, 32.1678, 32.1678**2, 335.12, 240.89, "Buy"], ... [0.8, 1.0, 0.69, 0.79, 1.876, 1.876**2, 14.12, 19.78, "Hold"], ... [0.66, 0.69, 1.0, 0.86, 7, 7**2, 210.9, 140.6, "Buy"], ... [0.72, 0.79, 0.86, 1.0, 213.76, 213.76**2, 2807, 3678, "Sell"], ... ], columns=cidx, index=iidx).style Second we will format the display and, since our table is quite wide, will hide the repeated level-0 of the index: >>> (styler.format(subset="Equity", precision=2) ... .format(subset="Stats", precision=1, thousands=",") ... .format(subset="Rating", formatter=str.upper) ... .format_index(escape="latex", axis=1) ... .format_index(escape="latex", axis=0) ... .hide(level=0, axis=0)) # doctest: +SKIP Note that one of the string entries of the index and column headers is "H&M". Without applying the `escape="latex"` option to the `format_index` method the resultant LaTeX will fail to render, and the error returned is quite difficult to debug. Using the appropriate escape the "&" is converted to "\\&". Thirdly we will apply some (CSS-HTML) styles to our object. We will use a builtin method and also define our own method to highlight the stock recommendation: >>> def rating_color(v): ... if v == "Buy": color = "#33ff85" ... elif v == "Sell": color = "#ff5933" ... else: color = "#ffdd33" ... return f"color: {color}; font-weight: bold;" >>> (styler.background_gradient(cmap="inferno", subset="Equity", vmin=0, vmax=1) ... .map(rating_color, subset="Rating")) # doctest: +SKIP All the above styles will work with HTML (see below) and LaTeX upon conversion: .. figure:: ../../_static/style/latex_stocks_html.png However, we finally want to add one LaTeX only style (from the {graphicx} package), that is not easy to convert from CSS and pandas does not support it. Notice the `--latex` flag used here, as well as `--rwrap` to ensure this is formatted correctly and not ignored upon conversion. >>> styler.map_index( ... lambda v: "rotatebox:{45}--rwrap--latex;", level=2, axis=1 ... ) # doctest: +SKIP Finally we render our LaTeX adding in other options as required: >>> styler.to_latex( ... caption="Selected stock correlation and simple statistics.", ... clines="skip-last;data", ... convert_css=True, ... position_float="centering", ... multicol_align="|c|", ... hrules=True, ... ) # doctest: +SKIP \begin{table} \centering \caption{Selected stock correlation and simple statistics.} \begin{tabular}{llrrrrrrrrl} \toprule & & \multicolumn{4}{|c|}{Equity} & \multicolumn{4}{|c|}{Stats} & Rating \\ & & \multicolumn{2}{|c|}{Energy} & \multicolumn{2}{|c|}{Consumer} & \multicolumn{4}{|c|}{} & \\ & & \rotatebox{45}{BP} & \rotatebox{45}{Shell} & \rotatebox{45}{H\&M} & \rotatebox{45}{Unilever} & \rotatebox{45}{Std Dev} & \rotatebox{45}{Variance} & \rotatebox{45}{52w High} & \rotatebox{45}{52w Low} & \rotatebox{45}{} \\ \midrule \multirow[c]{2}{*}{Energy} & BP & {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 & {\cellcolor[HTML]{FCA50A}} \color[HTML]{000000} 0.80 & {\cellcolor[HTML]{EB6628}} \color[HTML]{F1F1F1} 0.66 & {\cellcolor[HTML]{F68013}} \color[HTML]{F1F1F1} 0.72 & 32.2 & 1,034.8 & 335.1 & 240.9 & \color[HTML]{33FF85} \bfseries BUY \\ & Shell & {\cellcolor[HTML]{FCA50A}} \color[HTML]{000000} 0.80 & {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 & {\cellcolor[HTML]{F1731D}} \color[HTML]{F1F1F1} 0.69 & {\cellcolor[HTML]{FCA108}} \color[HTML]{000000} 0.79 & 1.9 & 3.5 & 14.1 & 19.8 & \color[HTML]{FFDD33} \bfseries HOLD \\ \cline{1-11} \multirow[c]{2}{*}{Consumer} & H\&M & {\cellcolor[HTML]{EB6628}} \color[HTML]{F1F1F1} 0.66 & {\cellcolor[HTML]{F1731D}} \color[HTML]{F1F1F1} 0.69 & {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 & {\cellcolor[HTML]{FAC42A}} \color[HTML]{000000} 0.86 & 7.0 & 49.0 & 210.9 & 140.6 & \color[HTML]{33FF85} \bfseries BUY \\ & Unilever & {\cellcolor[HTML]{F68013}} \color[HTML]{F1F1F1} 0.72 & {\cellcolor[HTML]{FCA108}} \color[HTML]{000000} 0.79 & {\cellcolor[HTML]{FAC42A}} \color[HTML]{000000} 0.86 & {\cellcolor[HTML]{FCFFA4}} \color[HTML]{000000} 1.00 & 213.8 & 45,693.3 & 2,807.0 & 3,678.0 & \color[HTML]{FF5933} \bfseries SELL \\ \cline{1-11} \bottomrule \end{tabular} \end{table} .. figure:: ../../_static/style/latex_stocks.png Tdeepcopyselectorr:rrpF overwrite)stoprvlrSr longtablez<`position_float` cannot be used in 'longtable' `environment`) raggedright raggedleft centeringzR`position_float` should be one of 'raggedright', 'raggedleft', 'centering', got: ''rzstyler.latex.hrulestoprulez:toprulemidrulez:midrule bottomrulez :bottomrulerz:{§}styler.sparse.indexstyler.sparse.columnszstyler.latex.environmentzstyler.latex.multicol_alignzstyler.latex.multirow_align)rrrrrrrrstyler.render.encodingrr)_copyrAset_table_stylesr>rTrlen_get_numeric_datato_listrangerWrX hide_index_ enumeratehidden_columnsrVr replace set_caption _render_latexrRstrr)rNrrrrrrrrCrrrrrrrrobjstyletable_selectors_original_columns numeric_colslevelci_rds r9rezStyler.to_latex\shjj$j'  ,-1,=,= >5U:  >   $  -!M?8KLM !  / !% 1 1  *DII4E4E0F GDII 99668@@HHJL 1DII Mtzz112 Ht'7'7'>CG  H"499#4#45 AT000!9;|9KGQTM   -!M?8KLM !    (Qxj>BC !  k) R%OO +,A/  .1^ HTML element in the format: ```` If not given uses Styler's initially assigned value. table_attributes : str, optional Attributes to assign within the `
` HTML element in the format: ``
>`` If not given defaults to Styler's preexisting value. 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. .. versionadded:: 1.4.0 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 column. Defaults to ``pandas.options.styler.sparse.columns`` value. .. versionadded:: 1.4.0 bold_headers : bool, optional Adds "font-weight: bold;" as a CSS property to table style header cells. .. versionadded:: 1.4.0 caption : str, optional Set, or overwrite, the caption on Styler before rendering. .. versionadded:: 1.4.0 max_rows : int, optional The maximum number of rows that will be rendered. Defaults to ``pandas.options.styler.render.max_rows/max_columns``. .. versionadded:: 1.4.0 max_columns : int, optional The maximum number of columns that will be rendered. Defaults to ``pandas.options.styler.render.max_columns``, which is None. Rows and columns may be reduced if the number of total elements is large. This value is set to ``pandas.options.styler.render.max_elements``, which is 262144 (18 bit browser rendering). .. versionadded:: 1.4.0 %(encoding)s doctype_html : bool, default False Whether to output a fully structured HTML file including all HTML elements, or just the core ``
... TrNrrthzfont-weight: bold;rFrr)rrrmax_colsrrrrr)rset_uuidset_table_attributesr rr _render_htmlr)rNrrrBrrrrCrrrrrrrr_s r9r`zStyler.to_htmlsZjj$j'  LL $   $ $%5 6  %&;>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) >>> df.style.to_string() ' A B\n0 1 3\n1 2 4\n' TrNrr)rrrrrr)rr _render_stringr) rNrrrrrrrrtexts r9rzStyler.to_stringlsjjj$j'  %&;`` 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 ------- Styler See Also -------- Styler.set_table_styles: Set the table styles included within the ``' '
  A B
' ' ' ' ' ' ' ' ' ' ' ' ' '
0
1
' z>Classes render only if `classes` has unique index and columns.Nrv) rWrirTrj reindex_liker>r itertuplespdisnar cell_context)rNclassesrrow_tupcvalues r9set_td_classeszStyler.set_td_classess~}}&&goo.G.GP &&tyy1#G$6$6$89 ;JAw%gabk2 ;5%2+03E D%%q!f- ; ;  rPc|jjr|jjs td|jD]}|jj |}||}|j D]c\}}|rt j|rt|}|jj |}|j||fj|ey)a Update the state of the ``Styler`` for data cells. Collects a mapping of {index_label: [('', ''), ..]}. Parameters ---------- attrs : DataFrame should contain strings of ': ;: ' Whitespace shouldn't matter and the final trailing ';' shouldn't matter. zN`Styler.apply` and `.map` are not compatible with non-unique index or columns.N) rWrirTrjget_locitemsrrrctxextend) rNattrscnjserrnrcss_listis r9 _update_ctxzStyler._update_ctxszz##4<<+A+A4  -- 2B $$R(A)C 2ABGGAJ6q9JJ&&r*!Q ''1  2 2rPc2|jD]}||}|jD]n\}}|rtj|rt |}|dk(r!|j ||fj |O|j||fj |py)a  Update the state of the ``Styler`` for header cells. Collects a mapping of {index_label: [('', ''), ..]}. Parameters ---------- attrs : Series Should contain strings of ': ;: ', and an integer index. Whitespace shouldn't matter and the final trailing ';' shouldn't matter. axis : int Identifies whether the ctx object being updated is the index or columns rN)rTrrrr ctx_indexr ctx_columns)rNraxisrrrrrs r9_update_ctx_headerzStyler._update_ctx_headers  >A(C  >1BGGAJ6q919NNAq6*11(;$$aV,33H= > >rPc t||j}gd}gd}|D]}t||t|||D]2}t||}t|||rt j |n|4|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 - concatenated stylers Non-data dependent attributes [copied and exported]: - css - hidden index state and hidden columns state (.hide_index_, .hide_columns_) - table_attributes - table_styles - applied styles (_todo) ) r hide_columns_hide_column_nameshide_index_namesrBrDrCr?r@template_latextemplate_html_styletemplate_html_table template_html)cssrY_display_funcs_display_funcs_index_display_funcs_columns hidden_rowsrrrrr_todorArk)typer>setattrgetattrcopyr)rNrstylershallowdeepattrvals r9rz Styler._copy7s2d II   " 7D FD'$"5 6 7 KD$%C FD$--"4c J K rPc&|jdS)NFrrras r9__copy__zStyler.__copy__|szz5z))rPc&|jdS)NTrr)rNmemos r9 __deepcopy__zStyler.__deepcopy__szz4z((rPc t|j|j}|jDcgc]}t |r|}}|jDcgc]}t |r|}}|D]}t ||t ||t|j|D]}t||ycc}wcc}w)a Reset the ``Styler``, removing any previously applied styles. Returns None. Examples -------- >>> df = pd.DataFrame({'A': [1, 2], 'B': [3, np.nan]}) After any added style: >>> df.style.highlight_null(color='yellow') # doctest: +SKIP Remove it with: >>> df.style.clear() # doctest: +SKIP Please see: `Table Visualization <../../user_guide/style.ipynb>`_ for more examples. r?N) r<r>r?__dict__callablerrset differencedelattr)rN clean_copya clean_attrs self_attrsrs r9clearz Styler.clears,DIIDII6 ","5"5IQXa[qI I!%BAhqkaB B ;D D$ D 9 : ; O..{; D D$  JBsB6B6B;&B;c 4| tdn|}t|}|jj|}|jr t }n|||fi|}t |t st |tjstdt|d|j|jk7r1tdt|d|jd|jt ||j|j}n_|jj|}|dk(r|j |fddi|}n)|j"j |fddi|j"}t |t$rtdt|ddt|d |d nd d }t'|jj)|jsDt|j+d |jj|jjt'|jj)|jsDt|j+d|jj|jj|j-||S)Nz 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: rWrTrrz resulted in the apply method collapsing to a Series. Usually, this is the result of the function returning a single value, instead of list-like.zU created invalid {0} labels. Usually, this is the result of the function returning a rrz which contains invalid labels, or returning an incorrectly shaped, list-like object which cannot be mapped to labels, possibly due to applying the function along the wrong axis. Result {0} has shape: {1} Expected {0} shape: {2}rWrT)slicer r>locemptyrrRnpndarrayrSreprshaperVrWrT_get_axis_numberapplyTrallisinrMr)rNr8rsubsetrr>resultmsgs r9_applyz Styler._applysM!'tF#F+yy}}V$ ::[F \$)&)Ffi0!&"**5##DJ<0GH::-$#DJ<0--3\\N;++/::,8 #6T\\R99--d3Dqy#D;q;F;%d==f=?? ff %DJ<(67  T |$6+x=>, - 6<<$$TZZ01SZZ1C1CTZZEUEUVW W6>>&&t||45 9fnn&:&:DLL>> 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') # doctest: +SKIP >>> df.style.apply(highlight_max, color='blue', axis=1) # doctest: +SKIP >>> df.style.apply(highlight_max, color='green', axis=None) # doctest: +SKIP Using ``subset`` to restrict application to a single column or multiple columns >>> df.style.apply(highlight_max, color='red', subset="A") ... # doctest: +SKIP >>> df.style.apply(highlight_max, color='red', subset=["A", "B"]) ... # doctest: +SKIP 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))) ... # doctest: +SKIP >>> df.style.apply(highlight_max, color='red', subset=(slice(0, 5, 2), "A")) ... # doctest: +SKIP Using a function which returns a Series / DataFrame of unequal length but containing valid index labels >>> df = pd.DataFrame([[1, 2], [3, 4], [4, 6]], index=["A1", "A2", "Total"]) >>> total_style = pd.Series("font-weight: bold;", index=["Total"]) >>> df.style.apply(lambda s: total_style) # doctest: +SKIP See `Table Visualization <../../user_guide/style.ipynb>`_ user guide for more details. ct|dS)Nr@rinstances r9zStyler.apply..4s gh9rPrrZ)rNr8rr=rs r9r9z Styler.applys0p  9D$;OQW X  rPr9c l|jj|}|dk(r |jn |j}t ||}t |j jdd|f}|dk(r|j|fddi|} n|dk(r|j|fi|} |j ||S)Nrr9rmap) r>r8rWrTr!rrr2r9rJr) rNr8rrmethodrrlevels_r>r>s r9 _apply_indexzStyler._apply_index8syy))$/ AIdjj4<<!%-'++AwJ7 W TZZ7177F u_TXXd-f-F - rPz level-wiserJ elementwisez:take a Series and return a string array of the same lengthz>the index as a Series, if an Index, or a level of a MultiIndexz3an identically sized array of CSS styles as stringssz3np.where(s == "B", "background-color: yellow;", "")z<["background-color: yellow;" if "x" in v else "" for v in s]) thiswisealtaltwiser8 input_note output_notevarretret2c L|jjd|||df|f|S)a  Apply a CSS-styling function to the index or column headers, {wise}. Updates the HTML representation with the result. .. versionadded:: 1.4.0 .. versionadded:: 2.1.0 Styler.applymap_index was deprecated and renamed to Styler.map_index. Parameters ---------- func : function ``func`` should {func}. axis : {{0, 1, "index", "columns"}} The headers over which to apply the function. level : int, str, list, optional If index is MultiIndex the level(s) over which to apply the function. **kwargs : dict Pass along to ``func``. Returns ------- Styler See Also -------- Styler.{alt}_index: Apply a CSS-styling function to headers {altwise}. Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise. Styler.map: Apply a CSS-styling function elementwise. Notes ----- Each input to ``func`` will be {input_note}. The output of ``func`` should be {output_note}, in the format 'attribute: value; attribute2: value2; ...' or, if nothing is to be applied to that element, an empty string or ``None``. Examples -------- Basic usage to conditionally highlight values in the index. >>> df = pd.DataFrame([[1,2], [3,4]], index=["A", "B"]) >>> def color_b(s): ... return {ret} >>> df.style.{this}_index(color_b) # doctest: +SKIP .. figure:: ../../_static/style/appmaphead1.png Selectively applying to specific levels of MultiIndex columns. >>> midx = pd.MultiIndex.from_product([['ix', 'jy'], [0, 1], ['x3', 'z4']]) >>> df = pd.DataFrame([np.arange(8)], columns=midx) >>> def highlight_x({var}): ... return {ret2} >>> df.style.{this}_index(highlight_x, axis="columns", level=[0, 2]) ... # doctest: +SKIP .. figure:: ../../_static/style/appmaphead2.png ct|dSNrMrDrEs r9rGz$Styler.apply_index.. >!BrPr9rHrNr8rrrs r9 apply_indexzStyler.apply_indexNs5\ BtUG,   rPz!take a scalar and return a stringz=an index value, if an Index, or a level value of a MultiIndexzCSS styles as a stringvz1"background-color: yellow;" if v == "B" else Nonez1"background-color: yellow;" if "x" in v else Nonec L|jjd|||df|f|S)Nct|dSr[rDrEs r9rGz"Styler.map_index..r\rPrJrHr]s r9 map_indexzStyler.map_indexs4( BtUE*   rPc ttjdtt|j|||fi|S)a Apply a CSS-styling function to the index or column headers, elementwise. .. deprecated:: 2.1.0 Styler.applymap_index has been deprecated. Use Styler.map_index instead. Parameters ---------- func : function ``func`` should take a scalar and return a string. axis : {{0, 1, "index", "columns"}} The headers over which to apply the function. level : int, str, list, optional If index is MultiIndex the level(s) over which to apply the function. **kwargs : dict Pass along to ``func``. Returns ------- Styler zHStyler.applymap_index has been deprecated. Use Styler.map_index instead. stacklevel)warningswarn FutureWarningrrbr]s r9applymap_indexzStyler.applymap_indexs8:  V ') t~~dD%:6::rPc t|fi|}| tdd}t|}|jj|j |}|j ||Sr)rrr r>r2rJr)rNr8r=rr>s r9_mapz Styler._mapsYt&v& >]F#F+v&**40   rPc H|jjd||f|f|S)ai Apply a CSS-styling function elementwise. Updates the HTML representation with the result. Parameters ---------- func : function ``func`` should take a scalar and return a string. %(subset)s **kwargs : dict Pass along to ``func``. Returns ------- Styler See Also -------- Styler.map_index: Apply a CSS-styling function to headers elementwise. Styler.apply_index: Apply a CSS-styling function to headers level-wise. 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.map(color_negative, color='red') # doctest: +SKIP Using ``subset`` to restrict application to a single column or multiple columns >>> df.style.map(color_negative, color='red', subset="A") ... # doctest: +SKIP >>> df.style.map(color_negative, color='red', subset=["A", "B"]) ... # doctest: +SKIP Using a 2d input to ``subset`` to select rows in addition to columns >>> df.style.map(color_negative, color='red', ... subset=([0,1,2], slice(None))) # doctest: +SKIP >>> df.style.map(color_negative, color='red', subset=(slice(0,5,2), "A")) ... # doctest: +SKIP See `Table Visualization <../../user_guide/style.ipynb>`_ user guide for more details. ct|dS)NrkrDrEs r9rGzStyler.map..'s gh7rPrHrNr8r=rs r9rJz Styler.maps,n  7$ P  rPc rtjdtt|j||fi|S)a Apply a CSS-styling function elementwise. .. deprecated:: 2.1.0 Styler.applymap has been deprecated. Use Styler.map instead. Parameters ---------- func : function ``func`` should take a scalar and return a string. %(subset)s **kwargs : dict Pass along to ``func``. Returns ------- Styler z`` HTML element. These are items in addition to automatic (by default) ``id`` attribute. Parameters ---------- attributes : str Returns ------- Styler See Also -------- Styler.set_table_styles: Set the table styles included within the ``