Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

DOC: clarify Series.map behavior for categorical dtype #62338

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

Open
Talyahav17 wants to merge 7 commits into pandas-dev:main
base: main
Choose a base branch
Loading
from Talyahav17:doc/clarify-categorical-map
Open
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
16 changes: 16 additions & 0 deletions pandas/core/arrays/categorical.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1585,6 +1585,22 @@ def map(

>>> cat.map({"a": "first", "b": "second"}, na_action=None)
Index(['first', 'second', nan], dtype='str')

The mapping function is applied to categories, not to each value. It is
therefore only called once per unique category, and the result reused for
all occurrences:

>>> cat = pd.Categorical(["a", "a", "b"])
>>> calls = []
>>> def f(x):
... calls.append(x)
... return x.upper()
>>> result = cat.map(f)
>>> result
['A', 'A', 'B']
Categories (2, str): ['A', 'B']
>>> calls
['a', 'b']
"""
assert callable(mapper) or is_dict_like(mapper)

Expand Down
28 changes: 28 additions & 0 deletions pandas/core/series.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4419,6 +4419,34 @@ def map(
2 NaN
3 I am a rabbit
dtype: object

For categorical data, the function is only applied to the categories:

>>> s = pd.Series(list("cabaa"))
>>> s.map(print)
c
a
b
a
a
0 None
1 None
2 None
3 None
4 None
dtype: object

>>> s_cat = s.astype("category")
>>> s_cat.map(print) # function called once per unique category
a
b
c
0 None
1 None
2 None
3 None
4 None
dtype: object
"""
if func is None:
if "arg" in kwargs:
Expand Down
Loading

AltStyle によって変換されたページ (->オリジナル) /