""" Module for applying conditional formatting to DataFrames and Series. """ from __future__ import annotations from contextlib import contextmanager import copy from functools import partial import operator from typing import ( Any, Callable, Hashable, Sequence, ) import warnings import numpy as np from pandas._config import get_option from pandas._typing import ( Axis, FilePathOrBuffer, FrameOrSeries, FrameOrSeriesUnion, IndexLabel, Scalar, ) from pandas.compat._optional import import_optional_dependency from pandas.util._decorators import doc import pandas as pd from pandas import ( IndexSlice, RangeIndex, ) from pandas.api.types import is_list_like from pandas.core import generic import pandas.core.common as com from pandas.core.frame import ( DataFrame, Series, ) from pandas.core.generic import NDFrame from pandas.io.formats.format import save_to_buffer jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.") from pandas.io.formats.style_render import ( CSSProperties, CSSStyles, StylerRenderer, Subset, Tooltips, maybe_convert_css_to_tuples, non_reducing_slice, ) try: from matplotlib import colors import matplotlib.pyplot as plt has_mpl = True except ImportError: has_mpl = False no_mpl_message = "{0} requires matplotlib." @contextmanager def _mpl(func: Callable): if has_mpl: yield plt, colors else: raise ImportError(no_mpl_message.format(func.__name__)) class Styler(StylerRenderer): r""" 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 ```` 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. .. 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`` 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`` """ def __init__( self, data: FrameOrSeriesUnion, precision: int | None = None, table_styles: CSSStyles | None = None, uuid: str | None = None, caption: str | tuple | None = None, table_attributes: str | None = None, cell_ids: bool = True, na_rep: str | None = None, uuid_len: int = 5, decimal: str = ".", thousands: str | None = None, escape: str | None = None, ): super().__init__( data=data, uuid=uuid, uuid_len=uuid_len, table_styles=table_styles, table_attributes=table_attributes, caption=caption, cell_ids=cell_ids, ) # validate ordered args self.precision = precision # can be removed on set_precision depr cycle self.na_rep = na_rep # can be removed on set_na_rep depr cycle self.format( formatter=None, precision=precision, na_rep=na_rep, escape=escape, decimal=decimal, thousands=thousands, ) def _repr_html_(self) -> str: """ Hooks into Jupyter notebook rich display system. """ return self.render() def render( self, sparse_index: bool | None = None, sparse_columns: bool | None = None, **kwargs, ) -> str: """ 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 """ if sparse_index is None: sparse_index = get_option("styler.sparse.index") if sparse_columns is None: sparse_columns = get_option("styler.sparse.columns") return self._render_html(sparse_index, sparse_columns, **kwargs) def set_tooltips( self, ttips: DataFrame, props: CSSProperties | None = None, css_class: str | None = None, ) -> Styler: """ 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 ------- self : 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).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;') """ if not self.cell_ids: # tooltips not optimised for individual cell check. requires reasonable # redesign and more extensive code for a feature that might be rarely used. raise NotImplementedError( "Tooltips can only render with 'cell_ids' is True." ) if not ttips.index.is_unique or not ttips.columns.is_unique: raise KeyError( "Tooltips render only if `ttips` has unique index and columns." ) if self.tooltips is None: # create a default instance if necessary self.tooltips = Tooltips() self.tooltips.tt_data = ttips if props: self.tooltips.class_properties = props if css_class: self.tooltips.class_name = css_class return self @doc( NDFrame.to_excel, klass="Styler", storage_options=generic._shared_docs["storage_options"], ) def to_excel( self, excel_writer, sheet_name: str = "Sheet1", na_rep: str = "", float_format: str | None = None, columns: Sequence[Hashable] | None = None, header: Sequence[Hashable] | bool = True, index: bool = True, index_label: IndexLabel | None = None, startrow: int = 0, startcol: int = 0, engine: str | None = None, merge_cells: bool = True, encoding: str | None = None, inf_rep: str = "inf", verbose: bool = True, freeze_panes: tuple[int, int] | None = None, ) -> None: from pandas.io.formats.excel import ExcelFormatter formatter = ExcelFormatter( self, na_rep=na_rep, cols=columns, header=header, float_format=float_format, index=index, index_label=index_label, merge_cells=merge_cells, inf_rep=inf_rep, ) formatter.write( excel_writer, sheet_name=sheet_name, startrow=startrow, startcol=startcol, freeze_panes=freeze_panes, engine=engine, ) def to_latex( self, buf: FilePathOrBuffer[str] | None = None, *, column_format: str | None = None, position: str | None = None, position_float: str | None = None, hrules: bool = False, label: str | None = None, caption: str | tuple | None = None, sparse_index: bool | None = None, sparse_columns: bool | None = None, multirow_align: str = "c", multicol_align: str = "r", siunitx: bool = False, encoding: str | None = None, convert_css: bool = False, ): r""" 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}{} 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}[] \\ 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{
}. 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`` 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 ``(, )`` 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.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 ``(, )`` 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 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 ````, 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() .. 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} """ obj = self._copy(deepcopy=True) # manipulate table_styles on obj, not self table_selectors = ( [style["selector"] for style in self.table_styles] if self.table_styles is not None else [] ) if column_format is not None: # add more recent setting to table_styles obj.set_table_styles( [{"selector": "column_format", "props": f":{column_format}"}], overwrite=False, ) elif "column_format" in table_selectors: pass # adopt what has been previously set in table_styles else: # create a default: set float, complex, int cols to 'r' ('S'), index to 'l' _original_columns = self.data.columns self.data.columns = RangeIndex(stop=len(self.data.columns)) numeric_cols = self.data._get_numeric_data().columns.to_list() self.data.columns = _original_columns column_format = "" if self.hide_index_ else "l" * self.data.index.nlevels for ci, _ in enumerate(self.data.columns): if ci not in self.hidden_columns: column_format += ( ("r" if not siunitx else "S") if ci in numeric_cols else "l" ) obj.set_table_styles( [{"selector": "column_format", "props": f":{column_format}"}], overwrite=False, ) if position: obj.set_table_styles( [{"selector": "position", "props": f":{position}"}], overwrite=False, ) if position_float: if position_float not in ["raggedright", "raggedleft", "centering"]: raise ValueError( f"`position_float` should be one of " f"'raggedright', 'raggedleft', 'centering', " f"got: '{position_float}'" ) obj.set_table_styles( [{"selector": "position_float", "props": f":{position_float}"}], overwrite=False, ) if hrules: obj.set_table_styles( [ {"selector": "toprule", "props": ":toprule"}, {"selector": "midrule", "props": ":midrule"}, {"selector": "bottomrule", "props": ":bottomrule"}, ], overwrite=False, ) if label: obj.set_table_styles( [{"selector": "label", "props": f":{{{label.replace(':', '§')}}}"}], overwrite=False, ) if caption: obj.set_caption(caption) if sparse_index is None: sparse_index = get_option("styler.sparse.index") if sparse_columns is None: sparse_columns = get_option("styler.sparse.columns") latex = obj._render_latex( sparse_index=sparse_index, sparse_columns=sparse_columns, multirow_align=multirow_align, multicol_align=multicol_align, convert_css=convert_css, ) return save_to_buffer(latex, buf=buf, encoding=encoding) def to_html( self, buf: FilePathOrBuffer[str] | None = None, *, table_uuid: str | None = None, table_attributes: str | None = None, encoding: str | None = None, doctype_html: bool = False, exclude_styles: bool = False, ): """ 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 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. 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 ``' '
' ' ' ' ' ' ' ' ' ' ' ' ' '
0
1
' """ if not classes.index.is_unique or not classes.columns.is_unique: raise KeyError( "Classes render only if `classes` has unique index and columns." ) classes = classes.reindex_like(self.data) for r, row_tup in enumerate(classes.itertuples()): for c, value in enumerate(row_tup[1:]): if not (pd.isna(value) or value == ""): self.cell_context[(r, c)] = str(value) return self def _update_ctx(self, attrs: DataFrame) -> None: """ 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. """ if not self.index.is_unique or not self.columns.is_unique: raise KeyError( "`Styler.apply` and `.applymap` are not compatible " "with non-unique index or columns." ) for cn in attrs.columns: for rn, c in attrs[[cn]].itertuples(): if not c: continue css_list = maybe_convert_css_to_tuples(c) i, j = self.index.get_loc(rn), self.columns.get_loc(cn) self.ctx[(i, j)].extend(css_list) def _copy(self, deepcopy: bool = False) -> Styler: """ 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) """ # GH 40675 styler = Styler( self.data, # populates attributes 'data', 'columns', 'index' as shallow uuid_len=self.uuid_len, ) shallow = [ # simple string or boolean immutables "hide_index_", "hide_columns_", "table_attributes", "cell_ids", "caption", ] deep = [ # nested lists or dicts "_display_funcs", "hidden_rows", "hidden_columns", "ctx", "cell_context", "_todo", "table_styles", "tooltips", ] for attr in shallow: setattr(styler, attr, getattr(self, attr)) for attr in deep: val = getattr(self, attr) setattr(styler, attr, copy.deepcopy(val) if deepcopy else val) return styler def __copy__(self) -> Styler: return self._copy(deepcopy=False) def __deepcopy__(self, memo) -> Styler: return self._copy(deepcopy=True) def clear(self) -> None: """ Reset the ``Styler``, removing any previously applied styles. Returns None. """ self.ctx.clear() self.tooltips = None self.cell_context.clear() self._todo.clear() self.hide_index_ = False self.hidden_columns = [] # self.format and self.table_styles may be dependent on user # input in self.__init__() def _apply( self, func: Callable[..., Styler], axis: Axis | None = 0, subset: Subset | None = None, **kwargs, ) -> Styler: subset = slice(None) if subset is None else subset subset = non_reducing_slice(subset) data = self.data.loc[subset] if axis is not None: result = data.apply(func, axis=axis, result_type="expand", **kwargs) result.columns = data.columns else: result = func(data, **kwargs) if not isinstance(result, DataFrame): if not isinstance(result, np.ndarray): raise TypeError( f"Function {repr(func)} must return a DataFrame or ndarray " f"when passed to `Styler.apply` with axis=None" ) if not (data.shape == result.shape): raise ValueError( f"Function {repr(func)} returned ndarray with wrong shape.\n" f"Result has shape: {result.shape}\n" f"Expected shape: {data.shape}" ) result = DataFrame(result, index=data.index, columns=data.columns) elif not ( result.index.equals(data.index) and result.columns.equals(data.columns) ): raise ValueError( f"Result of {repr(func)} must have identical " f"index and columns as the input" ) if result.shape != data.shape: raise ValueError( f"Function {repr(func)} returned the wrong shape.\n" f"Result has shape: {result.shape}\n" f"Expected shape: {data.shape}" ) self._update_ctx(result) return self def apply( self, func: Callable[..., Styler], axis: Axis | None = 0, subset: Subset | None = None, **kwargs, ) -> Styler: """ 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[]`, 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. **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") """ self._todo.append( (lambda instance: getattr(instance, "_apply"), (func, axis, subset), kwargs) ) return self def _applymap( self, func: Callable, subset: Subset | None = None, **kwargs ) -> Styler: func = partial(func, **kwargs) # applymap doesn't take kwargs? if subset is None: subset = IndexSlice[:] subset = non_reducing_slice(subset) result = self.data.loc[subset].applymap(func) self._update_ctx(result) return self def applymap( self, func: Callable, subset: Subset | None = None, **kwargs ) -> Styler: """ 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[]`, 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. **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") """ self._todo.append( (lambda instance: getattr(instance, "_applymap"), (func, subset), kwargs) ) return self def where( self, cond: Callable, value: str, other: str | None = None, subset: Subset | None = None, **kwargs, ) -> Styler: """ 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[]`, 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. **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;') """ warnings.warn( "this method is deprecated in favour of `Styler.applymap()`", FutureWarning, stacklevel=2, ) if other is None: other = "" return self.applymap( lambda val: value if cond(val, **kwargs) else other, subset=subset, ) def set_precision(self, precision: int) -> StylerRenderer: """ 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`. """ warnings.warn( "this method is deprecated in favour of `Styler.format(precision=..)`", FutureWarning, stacklevel=2, ) self.precision = precision return self.format(precision=precision, na_rep=self.na_rep) def set_table_attributes(self, attributes: str) -> Styler: """ Set the table attributes added to the ```` 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 ``