Skip to content

DOC: Styler docs - split PR from #39720 #40493

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 99 additions & 49 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,10 @@ def set_tooltips(
css_class: Optional[str] = None,
) -> Styler:
"""
Add string based tooltips that will appear in the `Styler` HTML result. These
tooltips are applicable only to`<td>` elements.
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

Expand All @@ -227,7 +229,7 @@ def set_tooltips(
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
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
Expand Down Expand Up @@ -671,21 +673,33 @@ def format(

def set_td_classes(self, classes: DataFrame) -> Styler:
"""
Add string based CSS class names to data cells that will appear within the
`Styler` HTML result. These classes are added within specified `<td>` elements.
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 values that must exist on the
underlying `Styler` data. None, NaN values, and empty strings will
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"])
Expand All @@ -707,16 +721,16 @@ def set_td_classes(self, classes: DataFrame) -> Styler:
Form of the output with new additional css classes,

>>> df = pd.DataFrame([[1]])
>>> css = pd.DataFrame(["other-class"])
>>> 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__" >'
'<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>'
' <tr><td class="data row0 col0 other-class" >1</td></tr>'
' </tbody>'
'</table>'
"""
Expand All @@ -736,7 +750,7 @@ def set_td_classes(self, classes: DataFrame) -> Styler:

def render(self, **kwargs) -> str:
"""
Render the built up styles to HTML.
Render the ``Styler`` including all applied styles to HTML.

Parameters
----------
Expand All @@ -753,7 +767,7 @@ def render(self, **kwargs) -> str:

Notes
-----
``Styler`` objects have defined the ``_repr_html_`` method
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
Expand All @@ -779,7 +793,7 @@ def render(self, **kwargs) -> str:

def _update_ctx(self, attrs: DataFrame) -> None:
"""
Update the state of the Styler for data cells.
Update the state of the ``Styler`` for data cells.

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

Expand Down Expand Up @@ -839,7 +853,7 @@ def __deepcopy__(self, memo) -> Styler:

def clear(self) -> None:
"""
Reset the styler, removing any previously applied styles.
Reset the ``Styler``, removing any previously applied styles.

Returns None.
"""
Expand Down Expand Up @@ -923,10 +937,11 @@ def apply(
Parameters
----------
func : function
``func`` should take a Series or DataFrame (depending
on ``axis``), and return an object with the same shape.
Must return a DataFrame with identical index and
column labels or an ndarray with same shape as input when ``axis=None``.
``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

Expand All @@ -944,13 +959,16 @@ def apply(
-------
self : Styler

See Also
--------
Styler.where: Apply CSS-styles based on a conditional function elementwise.
Styler.applymap: Apply a CSS-styling function elementwise.

Notes
-----
The output of ``func`` should be elements having CSS style as string or,
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``.
The output shape must match the input, i.e. if
``x`` is the input row, column, or table (depending on ``axis``),
then ``func(x).shape == x.shape`` should be ``True``.

This is similar to ``DataFrame.apply``, except that ``axis=None``
applies the function to the entire DataFrame at once,
Expand Down Expand Up @@ -1001,13 +1019,14 @@ def applymap(self, func: Callable, subset=None, **kwargs) -> Styler:

See Also
--------
Styler.where: Updates the HTML representation with a style which is
selected in accordance with the return value of a function.
Styler.where: Apply CSS-styles based on a conditional function elementwise.
Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.

Notes
-----
The output of ``func`` should be a CSS style as string or, if nothing is to be
applied, an empty string or ``None``.
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
--------
Expand All @@ -1030,7 +1049,7 @@ def where(
**kwargs,
) -> Styler:
"""
Apply a function elementwise.
Apply CSS-styles based on a conditional function elementwise.

Updates the HTML representation with a style which is
selected in accordance with the return value of a function.
Expand All @@ -1055,7 +1074,15 @@ def where(

See Also
--------
Styler.applymap: Updates the HTML representation with the result.
Styler.applymap: Apply a CSS-styling function elementwise.
Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.

Examples
--------
>>> def cond(v):
... return v > 1 and v != 4
>>> df = pd.DataFrame([[1, 2], [3, 4]])
>>> df.style.where(cond, value='color:red;', other='font-size:2em;')
"""
if other is None:
other = ""
Expand Down Expand Up @@ -1092,10 +1119,9 @@ def set_precision(self, precision: int) -> Styler:

def set_table_attributes(self, attributes: str) -> Styler:
"""
Set the table attributes.
Set the table attributes added to the ``<table>`` HTML element.

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

Parameters
----------
Expand All @@ -1105,6 +1131,13 @@ def set_table_attributes(self, attributes: str) -> Styler:
-------
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))
Expand All @@ -1116,23 +1149,23 @@ def set_table_attributes(self, attributes: str) -> Styler:

def export(self) -> List[Tuple[Callable, Tuple, Dict]]:
"""
Export the styles to applied to the current Styler.
Export the styles applied to the current ``Styler``.

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

Returns
-------
styles : list

See Also
--------
Styler.use: Set the styles on the current Styler.
Styler.use: Set the styles on the current ``Styler``.
"""
return self._todo

def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> Styler:
"""
Set the styles on the current Styler.
Set the styles on the current ``Styler``.

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

Expand All @@ -1147,14 +1180,14 @@ def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> Styler:

See Also
--------
Styler.export : Export the styles to applied to the current Styler.
Styler.export : Export the styles to applied to the current ``Styler``.
"""
self._todo.extend(styles)
return self

def set_uuid(self, uuid: str) -> Styler:
"""
Set the uuid for a Styler.
Set the uuid applied to ``id`` attributes of HTML elements.

Parameters
----------
Expand All @@ -1163,13 +1196,19 @@ def set_uuid(self, uuid: str) -> Styler:
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``.
"""
self.uuid = uuid
return self

def set_caption(self, caption: str) -> Styler:
"""
Set the caption on a Styler.
Set the text added to a ``<caption>`` HTML element.

Parameters
----------
Expand All @@ -1189,9 +1228,7 @@ def set_table_styles(
overwrite: bool = True,
) -> Styler:
"""
Set the table styles on a Styler.

These are placed in a ``<style>`` tag before the generated HTML table.
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.
Expand Down Expand Up @@ -1232,6 +1269,13 @@ def set_table_styles(
-------
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),
Expand Down Expand Up @@ -1295,7 +1339,7 @@ def set_table_styles(

def set_na_rep(self, na_rep: str) -> Styler:
"""
Set the missing data representation on a Styler.
Set the missing data representation on a ``Styler``.

.. versionadded:: 1.0.0

Expand Down Expand Up @@ -1505,7 +1549,8 @@ def css(rgba) -> str:

def set_properties(self, subset=None, **kwargs) -> Styler:
"""
Method to set one or more non-data dependent properties or each cell.
Set defined CSS-properties to each ``<td>`` HTML element within the given
subset.

Parameters
----------
Expand All @@ -1518,6 +1563,11 @@ def set_properties(self, subset=None, **kwargs) -> Styler:
-------
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))
Expand Down Expand Up @@ -1865,8 +1915,8 @@ def pipe(self, func: Callable, *args, **kwargs):
See Also
--------
DataFrame.pipe : Analogous method for DataFrame.
Styler.apply : Apply a function row-wise, column-wise, or table-wise to
modify the dataframe's styling.
Styler.apply : Apply a CSS-styling function column-wise, row-wise, or
table-wise.

Notes
-----
Expand Down Expand Up @@ -1915,7 +1965,7 @@ def pipe(self, func: Callable, *args, **kwargs):
class _Tooltips:
"""
An extension to ``Styler`` that allows for and manipulates tooltips on hover
of table data-cells in the HTML result.
of ``<td>`` cells in the HTML result.

Parameters
----------
Expand All @@ -1924,7 +1974,7 @@ class _Tooltips:
css_props: list-like, default; see Notes
List of (attr, value) tuples defining properties of the CSS class.
tooltips: DataFrame, default empty
DataFrame of strings aligned with underlying ``Styler`` data for tooltip
DataFrame of strings aligned with underlying Styler data for tooltip
display.

Notes
Expand Down Expand Up @@ -2025,7 +2075,7 @@ def _translate(self, styler_data: FrameOrSeriesUnion, uuid: str, d: Dict):
"""
Mutate the render dictionary to allow for tooltips:

- Add `<span>` HTML element to each data cells `display_value`. Ignores
- Add ``<span>`` HTML element to each data cells ``display_value``. Ignores
headers.
- Add table level CSS styles to control pseudo classes.

Expand Down