pandas.CategoricalIndex.map#

CategoricalIndex.map(mapper)[源代码]#

使用输入、输入、映射或函数映射值。

将索引值(其类别,而不是代码)映射到新类别。如果映射对应关系是一对一的,则结果为 CategoricalIndex 该属性与原始对象具有相同的顺序属性,否则为 Index 返回。

如果一个 dictSeries 使用映射到的任何未映射类别 NaN 。请注意,如果发生这种情况,则会引发 Index 将会被退还。

参数
mapper函数、DICT或系列

映射通信。

退货
Pandas.CategoricalIndex或Pandas.Index

映射的索引。

参见

Index.map

将映射对应应用于 Index

Series.map

将映射对应应用于 Series

Series.apply

将更复杂的函数应用于 Series

示例

>>> idx = pd.CategoricalIndex(['a', 'b', 'c'])
>>> idx
CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'],
                  ordered=False, dtype='category')
>>> idx.map(lambda x: x.upper())
CategoricalIndex(['A', 'B', 'C'], categories=['A', 'B', 'C'],
                 ordered=False, dtype='category')
>>> idx.map({'a': 'first', 'b': 'second', 'c': 'third'})
CategoricalIndex(['first', 'second', 'third'], categories=['first',
                 'second', 'third'], ordered=False, dtype='category')

如果映射是一对一的,则保留类别的顺序:

>>> idx = pd.CategoricalIndex(['a', 'b', 'c'], ordered=True)
>>> idx
CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'],
                 ordered=True, dtype='category')
>>> idx.map({'a': 3, 'b': 2, 'c': 1})
CategoricalIndex([3, 2, 1], categories=[3, 2, 1], ordered=True,
                 dtype='category')

如果映射不是一对一的,则 Index 返回:

>>> idx.map({'a': 'first', 'b': 'second', 'c': 'first'})
Index(['first', 'second', 'first'], dtype='object')

如果一个 dict ,则将所有未映射的类别映射到 NaN 结果就是一个 Index

>>> idx.map({'a': 'first', 'b': 'second'})
Index(['first', 'second', nan], dtype='object')