pandas.Categorical.map#
- Categorical.map(mapper, 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 aIndex
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 anIndex
will be returned.- Parameters:
- mapperfunction, dict, or Series
Mapping correspondence.
- na_action{None, ‘ignore’}, default None
If ‘ignore’, propagate NaN values, without passing them to the mapping correspondence.
- Returns:
- pandas.Categorical or pandas.Index
Mapped categorical.
See also
CategoricalIndex.map
Apply a mapping correspondence on a
CategoricalIndex
.Index.map
Apply a mapping correspondence on an
Index
.Series.map
Apply a mapping correspondence on a
Series
.Series.apply
Apply more complex functions on a
Series
.
Examples
>>> cat = pd.Categorical(["a", "b", "c"]) >>> cat ['a', 'b', 'c'] Categories (3, object): ['a', 'b', 'c'] >>> cat.map(lambda x: x.upper(), na_action=None) ['A', 'B', 'C'] Categories (3, object): ['A', 'B', 'C'] >>> cat.map({"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'] >>> cat.map({"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:>>> cat.map({"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
:>>> cat.map({"a": "first", "b": "second"}, na_action=None) Index(['first', 'second', nan], dtype='object')