, na_action=None)[source]#

Map categories using an input mapping or function.

Maps the categories to new categories. If the mapping correspondence is one-to-one the result is a Categorical which has the same order property as the original, otherwise a Index is returned. NaN values are unaffected.

If a dict or Series is used any unmapped category is mapped to NaN. Note that if this happens an Index will be returned.

mapperfunction, dict, or Series

Mapping correspondence.

na_action{None, ‘ignore’}, default None

If ‘ignore’, propagate NaN values, without passing them to the mapping correspondence.

pandas.Categorical or pandas.Index

Mapped categorical.

See also

Apply a mapping correspondence on a CategoricalIndex.

Apply a mapping correspondence on an Index.

Apply a mapping correspondence on a Series.


Apply more complex functions on a Series.


>>> cat = pd.Categorical(["a", "b", "c"])
>>> cat
['a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']
>>> x: x.upper(), na_action=None)
['A', 'B', 'C']
Categories (3, object): ['A', 'B', 'C']
>>>{"a": "first", "b": "second", "c": "third"}, na_action=None)
['first', 'second', 'third']
Categories (3, object): ['first', 'second', 'third']

If the mapping is one-to-one the ordering of the categories is preserved:

>>> cat = pd.Categorical(["a", "b", "c"], ordered=True)
>>> cat
['a', 'b', 'c']
Categories (3, object): ['a' < 'b' < 'c']
>>>{"a": 3, "b": 2, "c": 1}, na_action=None)
[3, 2, 1]
Categories (3, int64): [3 < 2 < 1]

If the mapping is not one-to-one an Index is returned:

>>>{"a": "first", "b": "second", "c": "first"}, na_action=None)
Index(['first', 'second', 'first'], dtype='object')

If a dict is used, all unmapped categories are mapped to NaN and the result is an Index:

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