diff --git a/doc/source/reference/style.rst b/doc/source/reference/style.rst index 5144f12fa373a..2256876c93e01 100644 --- a/doc/source/reference/style.rst +++ b/doc/source/reference/style.rst @@ -36,9 +36,9 @@ Style application :toctree: api/ Styler.apply - Styler.applymap + Styler.map Styler.apply_index - Styler.applymap_index + Styler.map_index Styler.format Styler.format_index Styler.relabel_index diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb index 7ae19dfe8021e..79b04ef57d9cf 100644 --- a/doc/source/user_guide/style.ipynb +++ b/doc/source/user_guide/style.ipynb @@ -1,7 +1,6 @@ { "cells": [ { - "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -352,15 +351,15 @@ "\n", "- Using [.set_table_styles()][table] to control broader areas of the table with specified internal CSS. Although table styles allow the flexibility to add CSS selectors and properties controlling all individual parts of the table, they are unwieldy for individual cell specifications. Also, note that table styles cannot be exported to Excel. \n", "- Using [.set_td_classes()][td_class] to directly link either external CSS classes to your data cells or link the internal CSS classes created by [.set_table_styles()][table]. See [here](#Setting-Classes-and-Linking-to-External-CSS). These cannot be used on column header rows or indexes, and also won't export to Excel. \n", - "- Using the [.apply()][apply] and [.applymap()][applymap] functions to add direct internal CSS to specific data cells. See [here](#Styler-Functions). As of v1.4.0 there are also methods that work directly on column header rows or indexes; [.apply_index()][applyindex] and [.applymap_index()][applymapindex]. Note that only these methods add styles that will export to Excel. These methods work in a similar way to [DataFrame.apply()][dfapply] and [DataFrame.map()][dfmap].\n", + "- Using the [.apply()][apply] and [.map()][map] functions to add direct internal CSS to specific data cells. See [here](#Styler-Functions). As of v1.4.0 there are also methods that work directly on column header rows or indexes; [.apply_index()][applyindex] and [.map_index()][mapindex]. Note that only these methods add styles that will export to Excel. These methods work in a similar way to [DataFrame.apply()][dfapply] and [DataFrame.map()][dfmap].\n", "\n", "[table]: ../reference/api/pandas.io.formats.style.Styler.set_table_styles.rst\n", "[styler]: ../reference/api/pandas.io.formats.style.Styler.rst\n", "[td_class]: ../reference/api/pandas.io.formats.style.Styler.set_td_classes.rst\n", "[apply]: ../reference/api/pandas.io.formats.style.Styler.apply.rst\n", - "[applymap]: ../reference/api/pandas.io.formats.style.Styler.applymap.rst\n", + "[map]: ../reference/api/pandas.io.formats.style.Styler.map.rst\n", "[applyindex]: ../reference/api/pandas.io.formats.style.Styler.apply_index.rst\n", - "[applymapindex]: ../reference/api/pandas.io.formats.style.Styler.applymap_index.rst\n", + "[mapindex]: ../reference/api/pandas.io.formats.style.Styler.map_index.rst\n", "[dfapply]: ../reference/api/pandas.DataFrame.apply.rst\n", "[dfmap]: ../reference/api/pandas.DataFrame.map.rst" ] @@ -565,13 +564,13 @@ "\n", "We use the following methods to pass your style functions. Both of those methods take a function (and some other keyword arguments) and apply it to the DataFrame in a certain way, rendering CSS styles.\n", "\n", - "- [.applymap()][applymap] (elementwise): accepts a function that takes a single value and returns a string with the CSS attribute-value pair.\n", + "- [.map()][map] (elementwise): accepts a function that takes a single value and returns a string with the CSS attribute-value pair.\n", "- [.apply()][apply] (column-/row-/table-wise): accepts a function that takes a Series or DataFrame and returns a Series, DataFrame, or numpy array with an identical shape where each element is a string with a CSS attribute-value pair. This method passes each column or row of your DataFrame one-at-a-time or the entire table at once, depending on the `axis` keyword argument. For columnwise use `axis=0`, rowwise use `axis=1`, and for the entire table at once use `axis=None`.\n", "\n", "This method is powerful for applying multiple, complex logic to data cells. We create a new DataFrame to demonstrate this.\n", "\n", "[apply]: ../reference/api/pandas.io.formats.style.Styler.apply.rst\n", - "[applymap]: ../reference/api/pandas.io.formats.style.Styler.applymap.rst" + "[map]: ../reference/api/pandas.io.formats.style.Styler.map.rst" ] }, { @@ -589,7 +588,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "For example we can build a function that colors text if it is negative, and chain this with a function that partially fades cells of negligible value. Since this looks at each element in turn we use ``applymap``." + "For example we can build a function that colors text if it is negative, and chain this with a function that partially fades cells of negligible value. Since this looks at each element in turn we use ``map``." ] }, { @@ -600,8 +599,8 @@ "source": [ "def style_negative(v, props=''):\n", " return props if v < 0 else None\n", - "s2 = df2.style.applymap(style_negative, props='color:red;')\\\n", - " .applymap(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)\n", + "s2 = df2.style.map(style_negative, props='color:red;')\\\n", + " .map(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)\n", "s2" ] }, @@ -699,13 +698,13 @@ "\n", "Similar application is achieved for headers by using:\n", " \n", - "- [.applymap_index()][applymapindex] (elementwise): accepts a function that takes a single value and returns a string with the CSS attribute-value pair.\n", + "- [.map_index()][mapindex] (elementwise): accepts a function that takes a single value and returns a string with the CSS attribute-value pair.\n", "- [.apply_index()][applyindex] (level-wise): accepts a function that takes a Series and returns a Series, or numpy array with an identical shape where each element is a string with a CSS attribute-value pair. This method passes each level of your Index one-at-a-time. To style the index use `axis=0` and to style the column headers use `axis=1`.\n", "\n", "You can select a `level` of a `MultiIndex` but currently no similar `subset` application is available for these methods.\n", "\n", "[applyindex]: ../reference/api/pandas.io.formats.style.Styler.apply_index.rst\n", - "[applymapindex]: ../reference/api/pandas.io.formats.style.Styler.applymap_index.rst" + "[mapindex]: ../reference/api/pandas.io.formats.style.Styler.map_index.rst" ] }, { @@ -714,7 +713,7 @@ "metadata": {}, "outputs": [], "source": [ - "s2.applymap_index(lambda v: \"color:pink;\" if v>4 else \"color:darkblue;\", axis=0)\n", + "s2.map_index(lambda v: \"color:pink;\" if v>4 else \"color:darkblue;\", axis=0)\n", "s2.apply_index(lambda s: np.where(s.isin([\"A\", \"B\"]), \"color:pink;\", \"color:darkblue;\"), axis=1)" ] }, @@ -831,7 +830,7 @@ "source": [ "## Finer Control with Slicing\n", "\n", - "The examples we have shown so far for the `Styler.apply` and `Styler.applymap` functions have not demonstrated the use of the ``subset`` argument. This is a useful argument which permits a lot of flexibility: it allows you to apply styles to specific rows or columns, without having to code that logic into your `style` function.\n", + "The examples we have shown so far for the `Styler.apply` and `Styler.map` functions have not demonstrated the use of the ``subset`` argument. This is a useful argument which permits a lot of flexibility: it allows you to apply styles to specific rows or columns, without having to code that logic into your `style` function.\n", "\n", "The value passed to `subset` behaves similar to slicing a DataFrame;\n", "\n", @@ -1034,7 +1033,7 @@ "outputs": [], "source": [ "props = 'font-family: \"Times New Roman\", Times, serif; color: #e83e8c; font-size:1.3em;'\n", - "df4.style.applymap(lambda x: props, subset=[1])" + "df4.style.map(lambda x: props, subset=[1])" ] }, { @@ -1321,7 +1320,7 @@ "source": [ "### Set properties\n", "\n", - "Use `Styler.set_properties` when the style doesn't actually depend on the values. This is just a simple wrapper for `.applymap` where the function returns the same properties for all cells." + "Use `Styler.set_properties` when the style doesn't actually depend on the values. This is just a simple wrapper for `.map` where the function returns the same properties for all cells." ] }, { @@ -1465,8 +1464,8 @@ "outputs": [], "source": [ "style1 = df2.style\\\n", - " .applymap(style_negative, props='color:red;')\\\n", - " .applymap(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)\\\n", + " .map(style_negative, props='color:red;')\\\n", + " .map(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)\\\n", " .set_table_styles([{\"selector\": \"th\", \"props\": \"color: blue;\"}])\\\n", " .hide(axis=\"index\")\n", "style1" @@ -1683,7 +1682,7 @@ " - `number-format`\n", " - `border-style` (for Excel-specific styles: \"hair\", \"mediumDashDot\", \"dashDotDot\", \"mediumDashDotDot\", \"dashDot\", \"slantDashDot\", or \"mediumDashed\")\n", "\n", - "Table level styles, and data cell CSS-classes are not included in the export to Excel: individual cells must have their properties mapped by the `Styler.apply` and/or `Styler.applymap` methods." + "Table level styles, and data cell CSS-classes are not included in the export to Excel: individual cells must have their properties mapped by the `Styler.apply` and/or `Styler.map` methods." ] }, { @@ -1693,7 +1692,7 @@ "outputs": [], "source": [ "df2.style.\\\n", - " applymap(style_negative, props='color:red;').\\\n", + " map(style_negative, props='color:red;').\\\n", " highlight_max(axis=0).\\\n", " to_excel('styled.xlsx', engine='openpyxl')" ] @@ -1783,8 +1782,8 @@ "outputs": [], "source": [ "df4 = pd.DataFrame([['text']])\n", - "df4.style.applymap(lambda x: 'color:green;')\\\n", - " .applymap(lambda x: 'color:red;')" + "df4.style.map(lambda x: 'color:green;')\\\n", + " .map(lambda x: 'color:red;')" ] }, { @@ -1793,8 +1792,8 @@ "metadata": {}, "outputs": [], "source": [ - "df4.style.applymap(lambda x: 'color:red;')\\\n", - " .applymap(lambda x: 'color:green;')" + "df4.style.map(lambda x: 'color:red;')\\\n", + " .map(lambda x: 'color:green;')" ] }, { @@ -1821,7 +1820,7 @@ "source": [ "df4.style.set_uuid('a_')\\\n", " .set_table_styles([{'selector': 'td', 'props': 'color:red;'}])\\\n", - " .applymap(lambda x: 'color:green;')" + " .map(lambda x: 'color:green;')" ] }, { @@ -1840,7 +1839,7 @@ "df4.style.set_uuid('b_')\\\n", " .set_table_styles([{'selector': 'td', 'props': 'color:red;'},\n", " {'selector': '.cls-1', 'props': 'color:blue;'}])\\\n", - " .applymap(lambda x: 'color:green;')\\\n", + " .map(lambda x: 'color:green;')\\\n", " .set_td_classes(pd.DataFrame([['cls-1']]))" ] }, @@ -1861,7 +1860,7 @@ " .set_table_styles([{'selector': 'td', 'props': 'color:red;'},\n", " {'selector': '.cls-1', 'props': 'color:blue;'},\n", " {'selector': 'td.data', 'props': 'color:yellow;'}])\\\n", - " .applymap(lambda x: 'color:green;')\\\n", + " .map(lambda x: 'color:green;')\\\n", " .set_td_classes(pd.DataFrame([['cls-1']]))" ] }, @@ -1884,7 +1883,7 @@ " .set_table_styles([{'selector': 'td', 'props': 'color:red;'},\n", " {'selector': '.cls-1', 'props': 'color:blue;'},\n", " {'selector': 'td.data', 'props': 'color:yellow;'}])\\\n", - " .applymap(lambda x: 'color:green !important;')\\\n", + " .map(lambda x: 'color:green !important;')\\\n", " .set_td_classes(pd.DataFrame([['cls-1']]))" ] }, diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index b10dd876050ae..c2041e4b9b7f7 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -241,6 +241,8 @@ Deprecations - Deprecated :func:`is_interval_dtype`, check ``isinstance(dtype, pd.IntervalDtype)`` instead (:issue:`52607`) - Deprecated :func:`is_period_dtype`, check ``isinstance(dtype, pd.PeriodDtype)`` instead (:issue:`52642`) - Deprecated :func:`is_sparse`, check ``isinstance(dtype, pd.SparseDtype)`` instead (:issue:`52642`) +- Deprecated :meth:`.Styler.applymap_index`. Use the new :meth:`.Styler.map_index` method instead (:issue:`52708`) +- Deprecated :meth:`.Styler.applymap`. Use the new :meth:`.Styler.map` method instead (:issue:`52708`) - Deprecated :meth:`DataFrame.applymap`. Use the new :meth:`DataFrame.map` method instead (:issue:`52353`) - Deprecated :meth:`DataFrame.swapaxes` and :meth:`Series.swapaxes`, use :meth:`DataFrame.transpose` or :meth:`Series.transpose` instead (:issue:`51946`) - Deprecated ``freq`` parameter in :class:`PeriodArray` constructor, pass ``dtype`` instead (:issue:`52462`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2ee1e0512de74..bae06b95ffb27 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3543,7 +3543,7 @@ def _to_latex_via_styler( # bold_rows is not a direct kwarg of Styler.to_latex render_kwargs = {} if render_kwargs is None else render_kwargs if render_kwargs.pop("bold_rows"): - styler.applymap_index(lambda v: "textbf:--rwrap;") + styler.map_index(lambda v: "textbf:--rwrap;") return styler.to_latex(buf=buf, **render_kwargs) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 181b623cd52a6..c1da80660cf45 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -16,6 +16,7 @@ Sequence, overload, ) +import warnings import numpy as np @@ -26,6 +27,7 @@ Substitution, doc, ) +from pandas.util._exceptions import find_stack_level import pandas as pd from pandas import ( @@ -206,7 +208,7 @@ class Styler(StylerRenderer): Notes ----- Most styling will be done by passing style functions into - ``Styler.apply`` or ``Styler.applymap``. Style functions should + ``Styler.apply`` or ``Styler.map``. Style functions should return values with strings containing CSS ``'attr: value'`` that will be applied to the indicated cells. @@ -306,8 +308,8 @@ def concat(self, other: Styler) -> Styler: For example adding a sub total row, or displaying metrics such as means, variance or counts. - Styles that are applied using the ``apply``, ``applymap``, ``apply_index`` - and ``applymap_index``, and formatting applied with ``format`` and + 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:: @@ -354,7 +356,7 @@ def concat(self, other: Styler) -> Styler: >>> other = (descriptors.style ... .highlight_max(axis=1, subset=(["Total", "Average"], slice(None))) ... .format(subset=("Average", slice(None)), precision=2, decimal=",") - ... .applymap(lambda v: "font-weight: bold;")) + ... .map(lambda v: "font-weight: bold;")) >>> styler = (df.style ... .highlight_max(color="salmon") ... .set_table_styles([{"selector": ".foot_row0", @@ -991,7 +993,7 @@ def to_latex( ... else: color = "#ffdd33" ... return f"color: {color}; font-weight: bold;" >>> (styler.background_gradient(cmap="inferno", subset="Equity", vmin=0, vmax=1) - ... .applymap(rating_color, subset="Rating")) # doctest: +SKIP + ... .map(rating_color, subset="Rating")) # doctest: +SKIP All the above styles will work with HTML (see below) and LaTeX upon conversion: @@ -1003,7 +1005,7 @@ def to_latex( as well as `--rwrap` to ensure this is formatted correctly and not ignored upon conversion. - >>> styler.applymap_index( + >>> styler.map_index( ... lambda v: "rotatebox:{45}--rwrap--latex;", level=2, axis=1 ... ) # doctest: +SKIP @@ -1514,7 +1516,7 @@ def _update_ctx(self, attrs: DataFrame) -> None: """ if not self.index.is_unique or not self.columns.is_unique: raise KeyError( - "`Styler.apply` and `.applymap` are not compatible " + "`Styler.apply` and `.map` are not compatible " "with non-unique index or columns." ) @@ -1745,9 +1747,9 @@ def apply( See Also -------- - Styler.applymap_index: Apply a CSS-styling function to headers elementwise. + Styler.map_index: Apply a CSS-styling function to headers elementwise. Styler.apply_index: Apply a CSS-styling function to headers level-wise. - Styler.applymap: Apply a CSS-styling function elementwise. + Styler.map: Apply a CSS-styling function elementwise. Notes ----- @@ -1813,7 +1815,7 @@ def _apply_index( if method == "apply": result = data.apply(func, axis=0, **kwargs) - elif method == "applymap": + elif method == "map": result = data.map(func, **kwargs) self._update_ctx_header(result, axis) @@ -1822,7 +1824,7 @@ def _apply_index( @doc( this="apply", wise="level-wise", - alt="applymap", + alt="map", altwise="elementwise", func="take a Series and return a string array of the same length", input_note="the index as a Series, if an Index, or a level of a MultiIndex", @@ -1845,6 +1847,9 @@ def apply_index( .. versionadded:: 1.4.0 + .. versionadded:: 2.1.0 + Styler.applymap_index was deprecated and renamed to Styler.map_index. + Parameters ---------- func : function @@ -1864,7 +1869,7 @@ def apply_index( -------- 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.applymap: Apply a CSS-styling function elementwise. + Styler.map: Apply a CSS-styling function elementwise. Notes ----- @@ -1905,7 +1910,7 @@ def apply_index( @doc( apply_index, - this="applymap", + this="map", wise="elementwise", alt="apply", altwise="level-wise", @@ -1916,7 +1921,7 @@ def apply_index( ret='"background-color: yellow;" if v == "B" else None', ret2='"background-color: yellow;" if "x" in v else None', ) - def applymap_index( + def map_index( self, func: Callable, axis: AxisInt | str = 0, @@ -1926,16 +1931,50 @@ def applymap_index( self._todo.append( ( lambda instance: getattr(instance, "_apply_index"), - (func, axis, level, "applymap"), + (func, axis, level, "map"), kwargs, ) ) return self - def _applymap( - self, func: Callable, subset: Subset | None = None, **kwargs + def applymap_index( + self, + func: Callable, + axis: AxisInt | str = 0, + level: Level | list[Level] | None = None, + **kwargs, ) -> Styler: - func = partial(func, **kwargs) # applymap doesn't take kwargs? + """ + 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 + """ + warnings.warn( + "Styler.applymap_index has been deprecated. Use Styler.map_index instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.map_index(func, axis, level, **kwargs) + + def _map(self, func: Callable, subset: Subset | None = None, **kwargs) -> Styler: + func = partial(func, **kwargs) # map doesn't take kwargs? if subset is None: subset = IndexSlice[:] subset = non_reducing_slice(subset) @@ -1944,9 +1983,7 @@ def _applymap( return self @Substitution(subset=subset_args) - def applymap( - self, func: Callable, subset: Subset | None = None, **kwargs - ) -> Styler: + def map(self, func: Callable, subset: Subset | None = None, **kwargs) -> Styler: """ Apply a CSS-styling function elementwise. @@ -1966,7 +2003,7 @@ def applymap( See Also -------- - Styler.applymap_index: Apply a CSS-styling function to headers elementwise. + 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. @@ -1981,30 +2018,60 @@ def applymap( >>> 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') # doctest: +SKIP + >>> df.style.map(color_negative, color='red') # doctest: +SKIP Using ``subset`` to restrict application to a single column or multiple columns - >>> df.style.applymap(color_negative, color='red', subset="A") + >>> df.style.map(color_negative, color='red', subset="A") ... # doctest: +SKIP - >>> df.style.applymap(color_negative, color='red', subset=["A", "B"]) + >>> 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.applymap(color_negative, color='red', + >>> df.style.map(color_negative, color='red', ... subset=([0,1,2], slice(None))) # doctest: +SKIP - >>> df.style.applymap(color_negative, color='red', subset=(slice(0,5,2), "A")) + >>> 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. """ self._todo.append( - (lambda instance: getattr(instance, "_applymap"), (func, subset), kwargs) + (lambda instance: getattr(instance, "_map"), (func, subset), kwargs) ) return self + @Substitution(subset=subset_args) + def applymap( + self, func: Callable, subset: Subset | None = None, **kwargs + ) -> Styler: + """ + Apply a CSS-styling function 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. + %(subset)s + **kwargs : dict + Pass along to ``func``. + + Returns + ------- + Styler + """ + warnings.warn( + "Styler.applymap has been deprecated. Use Styler.map instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.map(func, subset, **kwargs) + def set_table_attributes(self, attributes: str) -> Styler: """ Set the table attributes added to the ```` HTML element. @@ -2058,7 +2125,7 @@ def export(self) -> dict[str, Any]: The following items are exported since they are not generally data dependent: - - Styling functions added by the ``apply`` and ``applymap`` + - Styling functions added by the ``apply`` and ``map`` - Whether axes and names are hidden from the display, if unambiguous. - Table attributes - Table styles @@ -2104,7 +2171,7 @@ def use(self, styles: dict[str, Any]) -> Styler: styles : dict(str, Any) List of attributes to add to Styler. Dict keys should contain only: - "apply": list of styler functions, typically added with ``apply`` or - ``applymap``. + ``map``. - "table_attributes": HTML attributes, typically added with ``set_table_attributes``. - "table_styles": CSS selectors and properties, typically added with @@ -2893,7 +2960,7 @@ def set_properties(self, subset: Subset | None = None, **kwargs) -> Styler: Notes ----- - This is a convenience methods which wraps the :meth:`Styler.applymap` calling a + This is a convenience methods which wraps the :meth:`Styler.map` calling a function returning the CSS-properties independently of the data. Examples @@ -2906,7 +2973,7 @@ def set_properties(self, subset: Subset | None = None, **kwargs) -> Styler: more details. """ values = "".join([f"{p}: {v};" for p, v in kwargs.items()]) - return self.applymap(lambda x: values, subset=subset) + return self.map(lambda x: values, subset=subset) @Substitution(subset=subset_args) def bar( # pylint: disable=disallowed-name diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 5b608089945a2..3f4273648b4d2 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -247,7 +247,7 @@ def _compute(self): Execute the style functions built up in `self._todo`. Relies on the conventions that all style functions go through - .apply or .applymap. The append styles to apply as tuples of + .apply or .map. The append styles to apply as tuples of (application method, *args, **kwargs) """ @@ -1168,7 +1168,7 @@ def format( >>> df = pd.DataFrame({"A": [1, 0, -1]}) >>> pseudo_css = "number-format: 0§[Red](0)§-§@;" >>> filename = "formatted_file.xlsx" - >>> df.style.applymap(lambda v: pseudo_css).to_excel(filename) # doctest: +SKIP + >>> df.style.map(lambda v: pseudo_css).to_excel(filename) # doctest: +SKIP .. figure:: ../../_static/style/format_excel_css.png """ diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index d28296ec2e380..b8d41164792e0 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -254,7 +254,7 @@ def test_to_excel_with_openpyxl_engine(ext): df1 = DataFrame({"A": np.linspace(1, 10, 10)}) df2 = DataFrame({"B": np.linspace(1, 20, 10)}) df = pd.concat([df1, df2], axis=1) - styled = df.style.applymap( + styled = df.style.map( lambda val: f"color: {'red' if val < 0 else 'black'}" ).highlight_max() diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index b26d59b9bdebb..0220fceb6347f 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -131,7 +131,7 @@ def test_styler_to_excel_unstyled(engine): def test_styler_to_excel_basic(engine, css, attrs, expected): pytest.importorskip(engine) df = DataFrame(np.random.randn(1, 1)) - styler = df.style.applymap(lambda x: css) + styler = df.style.map(lambda x: css) with tm.ensure_clean(".xlsx") as path: with ExcelWriter(path, engine=engine) as writer: @@ -164,13 +164,13 @@ def test_styler_to_excel_basic_indexes(engine, css, attrs, expected): df = DataFrame(np.random.randn(1, 1)) styler = df.style - styler.applymap_index(lambda x: css, axis=0) - styler.applymap_index(lambda x: css, axis=1) + styler.map_index(lambda x: css, axis=0) + styler.map_index(lambda x: css, axis=1) null_styler = df.style - null_styler.applymap(lambda x: "null: css;") - null_styler.applymap_index(lambda x: "null: css;", axis=0) - null_styler.applymap_index(lambda x: "null: css;", axis=1) + null_styler.map(lambda x: "null: css;") + null_styler.map_index(lambda x: "null: css;", axis=0) + null_styler.map_index(lambda x: "null: css;", axis=1) with tm.ensure_clean(".xlsx") as path: with ExcelWriter(path, engine=engine) as writer: @@ -231,7 +231,7 @@ def test_styler_to_excel_border_style(engine, border_style): pytest.importorskip(engine) df = DataFrame(np.random.randn(1, 1)) - styler = df.style.applymap(lambda x: css) + styler = df.style.map(lambda x: css) with tm.ensure_clean(".xlsx") as path: with ExcelWriter(path, engine=engine) as writer: @@ -261,7 +261,7 @@ def custom_converter(css): return {"font": {"color": {"rgb": "111222"}}} df = DataFrame(np.random.randn(1, 1)) - styler = df.style.applymap(lambda x: "color: #888999") + styler = df.style.map(lambda x: "color: #888999") with tm.ensure_clean(".xlsx") as path: with ExcelWriter(path, engine="openpyxl") as writer: ExcelFormatter(styler, style_converter=custom_converter).write( diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py index 1867260fbc4b4..67f7e12fcc3c2 100644 --- a/pandas/tests/io/formats/style/test_html.py +++ b/pandas/tests/io/formats/style/test_html.py @@ -85,11 +85,9 @@ def test_exclude_styles(styler): def test_w3_html_format(styler): - styler.set_uuid("").set_table_styles( - [{"selector": "th", "props": "att2:v2;"}] - ).applymap(lambda x: "att1:v1;").set_table_attributes( - 'class="my-cls1" style="attr3:v3;"' - ).set_td_classes( + styler.set_uuid("").set_table_styles([{"selector": "th", "props": "att2:v2;"}]).map( + lambda x: "att1:v1;" + ).set_table_attributes('class="my-cls1" style="attr3:v3;"').set_td_classes( DataFrame(["my-cls2"], index=["a"], columns=["A"]) ).format( "{:.1f}" @@ -428,14 +426,14 @@ def test_sparse_options(sparse_index, sparse_columns): @pytest.mark.parametrize("index", [True, False]) @pytest.mark.parametrize("columns", [True, False]) -def test_applymap_header_cell_ids(styler, index, columns): +def test_map_header_cell_ids(styler, index, columns): # GH 41893 func = lambda v: "attr: val;" styler.uuid, styler.cell_ids = "", False if index: - styler.applymap_index(func, axis="index") + styler.map_index(func, axis="index") if columns: - styler.applymap_index(func, axis="columns") + styler.map_index(func, axis="columns") result = styler.to_html() @@ -493,9 +491,9 @@ def test_replaced_css_class_names(): styler_mi.index.names = ["n1", "n2"] styler_mi.hide(styler_mi.index[1:], axis=0) styler_mi.hide(styler_mi.columns[1:], axis=1) - styler_mi.applymap_index(lambda v: "color: red;", axis=0) - styler_mi.applymap_index(lambda v: "color: green;", axis=1) - styler_mi.applymap(lambda v: "color: blue;") + styler_mi.map_index(lambda v: "color: red;", axis=0) + styler_mi.map_index(lambda v: "color: green;", axis=1) + styler_mi.map(lambda v: "color: blue;") expected = dedent( """\