Skip to content

Remove DataFrame.applymap and Styler.applymap #57345

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 3 commits into from
Feb 11, 2024
Merged
Show file tree
Hide file tree
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
5 changes: 0 additions & 5 deletions doc/redirects.csv
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,6 @@ generated/pandas.DataFrame.align,../reference/api/pandas.DataFrame.align
generated/pandas.DataFrame.all,../reference/api/pandas.DataFrame.all
generated/pandas.DataFrame.any,../reference/api/pandas.DataFrame.any
generated/pandas.DataFrame.apply,../reference/api/pandas.DataFrame.apply
generated/pandas.DataFrame.applymap,../reference/api/pandas.DataFrame.applymap
generated/pandas.DataFrame.as_blocks,../reference/api/pandas.DataFrame.as_blocks
generated/pandas.DataFrame.asfreq,../reference/api/pandas.DataFrame.asfreq
generated/pandas.DataFrame.as_matrix,../reference/api/pandas.DataFrame.as_matrix
Expand Down Expand Up @@ -747,8 +746,6 @@ generated/pandas.Interval.overlaps,../reference/api/pandas.Interval.overlaps
generated/pandas.interval_range,../reference/api/pandas.interval_range
generated/pandas.Interval.right,../reference/api/pandas.Interval.right
generated/pandas.io.formats.style.Styler.apply,../reference/api/pandas.io.formats.style.Styler.apply
generated/pandas.io.formats.style.Styler.applymap,../reference/api/pandas.io.formats.style.Styler.map
generated/pandas.io.formats.style.Styler.applymap_index,../reference/api/pandas.io.formats.style.Styler.map_index
generated/pandas.io.formats.style.Styler.background_gradient,../reference/api/pandas.io.formats.style.Styler.background_gradient
generated/pandas.io.formats.style.Styler.bar,../reference/api/pandas.io.formats.style.Styler.bar
generated/pandas.io.formats.style.Styler.clear,../reference/api/pandas.io.formats.style.Styler.clear
Expand Down Expand Up @@ -1432,8 +1429,6 @@ reference/api/pandas.arrays.PandasArray,pandas.arrays.NumpyExtensionArray
reference/api/pandas.core.groupby.DataFrameGroupBy.backfill,pandas.core.groupby.DataFrameGroupBy.bfill
reference/api/pandas.core.groupby.GroupBy.backfill,pandas.core.groupby.DataFrameGroupBy.bfill
reference/api/pandas.core.resample.Resampler.backfill,pandas.core.resample.Resampler.bfill
reference/api/pandas.io.formats.style.Styler.applymap,pandas.io.formats.style.Styler.map
reference/api/pandas.io.formats.style.Styler.applymap_index,pandas.io.formats.style.Styler.map_index

# EWM -> ExponentialMovingWindow
reference/api/pandas.core.window.ewm.EWM.corr,pandas.core.window.ewm.ExponentialMovingWindow.corr
Expand Down
1 change: 0 additions & 1 deletion doc/source/reference/frame.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ Function application, GroupBy & window

DataFrame.apply
DataFrame.map
DataFrame.applymap
DataFrame.pipe
DataFrame.agg
DataFrame.aggregate
Expand Down
2 changes: 1 addition & 1 deletion doc/source/user_guide/10min.rst
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ will be completed:
df2.any df2.combine
df2.append df2.D
df2.apply df2.describe
df2.applymap df2.diff
df2.B df2.duplicated
df2.diff

As you can see, the columns ``A``, ``B``, ``C``, and ``D`` are automatically
tab completed. ``E`` and ``F`` are there as well; the rest of the attributes have been
Expand Down
3 changes: 1 addition & 2 deletions doc/source/whatsnew/v0.20.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,6 @@ Experimental support has been added to export ``DataFrame.style`` formats to Exc
For example, after running the following, ``styled.xlsx`` renders as below:

.. ipython:: python
:okwarning:

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
Expand All @@ -379,7 +378,7 @@ For example, after running the following, ``styled.xlsx`` renders as below:
df.iloc[0, 2] = np.nan
df
styled = (df.style
.applymap(lambda val: 'color:red;' if val < 0 else 'color:black;')
.map(lambda val: 'color:red;' if val < 0 else 'color:black;')
.highlight_max())
styled.to_excel('styled.xlsx', engine='openpyxl')

Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ Removal of prior version deprecations/changes
- :func:`read_excel`, :func:`read_json`, :func:`read_html`, and :func:`read_xml` no longer accept raw string or byte representation of the data. That type of data must be wrapped in a :py:class:`StringIO` or :py:class:`BytesIO` (:issue:`53767`)
- All arguments except the first ``path``-like argument in IO writers are now keyword only (:issue:`54229`)
- Changed the default value of ``observed`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` to ``True`` (:issue:`51811`)
- Removed :meth:`DataFrame.applymap`, :meth:`Styler.applymap` and :meth:`Styler.applymap_index` (:issue:`52364`)
- Removed ``DataFrame.bool`` and ``Series.bool`` (:issue:`51756`)
- Removed ``DataFrame.first`` and ``DataFrame.last`` (:issue:`53710`)
- Removed ``DataFrameGroupBy.grouper`` and ``SeriesGroupBy.grouper`` (:issue:`56521`)
Expand Down
55 changes: 0 additions & 55 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,6 @@
MergeHow,
MergeValidate,
MutableMappingT,
NaAction,
NaPosition,
NsmallestNlargestKeep,
PythonFuncType,
Expand Down Expand Up @@ -10150,60 +10149,6 @@ def infer(x):

return self.apply(infer).__finalize__(self, "map")

def applymap(
self, func: PythonFuncType, na_action: NaAction | None = None, **kwargs
) -> DataFrame:
"""
Apply a function to a Dataframe elementwise.

.. deprecated:: 2.1.0

DataFrame.applymap has been deprecated. Use DataFrame.map instead.

This method applies a function that accepts and returns a scalar
to every element of a DataFrame.

Parameters
----------
func : callable
Python function, returns a single value from a single value.
na_action : {None, 'ignore'}, default None
If 'ignore', propagate NaN values, without passing them to func.
**kwargs
Additional keyword arguments to pass as keywords arguments to
`func`.

Returns
-------
DataFrame
Transformed DataFrame.

See Also
--------
DataFrame.apply : Apply a function along input axis of DataFrame.
DataFrame.map : Apply a function along input axis of DataFrame.
DataFrame.replace: Replace values given in `to_replace` with `value`.

Examples
--------
>>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]])
>>> df
0 1
0 1.000 2.120
1 3.356 4.567

>>> df.map(lambda x: len(str(x)))
0 1
0 3 4
1 5 5
"""
warnings.warn(
"DataFrame.applymap has been deprecated. Use DataFrame.map instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
return self.map(func, na_action=na_action, **kwargs)

# ----------------------------------------------------------------------
# Merging / joining methods

Expand Down
4 changes: 2 additions & 2 deletions pandas/errors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -549,11 +549,11 @@ class CSSWarning(UserWarning):
Examples
--------
>>> df = pd.DataFrame({"A": [1, 1, 1]})
>>> df.style.applymap(lambda x: "background-color: blueGreenRed;").to_excel(
>>> df.style.map(lambda x: "background-color: blueGreenRed;").to_excel(
... "styled.xlsx"
... ) # doctest: +SKIP
CSSWarning: Unhandled color format: 'blueGreenRed'
>>> df.style.applymap(lambda x: "border: 1px solid red red;").to_excel(
>>> df.style.map(lambda x: "border: 1px solid red red;").to_excel(
... "styled.xlsx"
... ) # doctest: +SKIP
CSSWarning: Unhandled color format: 'blueGreenRed'
Expand Down
68 changes: 0 additions & 68 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
Callable,
overload,
)
import warnings

import numpy as np

Expand All @@ -23,7 +22,6 @@
Substitution,
doc,
)
from pandas.util._exceptions import find_stack_level

import pandas as pd
from pandas import (
Expand Down Expand Up @@ -2011,42 +2009,6 @@ def map_index(
)
return self

def applymap_index(
self,
func: Callable,
axis: AxisInt | str = 0,
level: Level | list[Level] | None = None,
**kwargs,
) -> Styler:
"""
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:
Expand Down Expand Up @@ -2117,36 +2079,6 @@ def map(self, func: Callable, subset: Subset | None = None, **kwargs) -> Styler:
)
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 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
"""
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 ``<table>`` HTML element.
Expand Down
8 changes: 0 additions & 8 deletions pandas/tests/frame/methods/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,3 @@ def test_map_invalid_na_action(float_frame):
# GH 23803
with pytest.raises(ValueError, match="na_action must be .*Got 'abc'"):
float_frame.map(lambda x: len(str(x)), na_action="abc")


def test_applymap_deprecated():
# GH52353
df = DataFrame({"a": [1, 2, 3]})
msg = "DataFrame.applymap has been deprecated. Use DataFrame.map instead."
with tm.assert_produces_warning(FutureWarning, match=msg):
df.applymap(lambda x: x)
12 changes: 0 additions & 12 deletions pandas/tests/io/formats/style/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1586,15 +1586,3 @@ def test_output_buffer(mi_styler, format):
# gh 47053
with tm.ensure_clean(f"delete_me.{format}") as f:
getattr(mi_styler, f"to_{format}")(f)


def test_deprecation_warning_for_usage_of_aaply_map_index_method_of_styler_object():
# 56717 https://github.com/pandas-dev/pandas/issues/56717
df = DataFrame([[1, 2], [3, 4]], index=["A", "B"])
msg = "Styler.applymap_index has been deprecated. Use Styler.map_index instead."

def color_b(s):
return "background-color:yellow;"

with tm.assert_produces_warning(FutureWarning, match=msg):
df.style.applymap_index(color_b, axis="columns")