pandas.CategoricalIndex.map#
- CategoricalIndex.map(mapper, na_action=None)[源代码]#
使用输入映射或函数映射值。
将索引的值(是其类别,而不是编码)映射到新类别。如果映射关系是一对一的,结果将是一个
CategoricalIndex,其顺序属性与原始索引相同,否则将返回一个Index。如果使用 dict 或
Series,任何未映射的类别都将映射到 NaN。请注意,如果发生这种情况,将返回一个Index。- Parameters:
- mapperfunction, dict, or Series
映射关系。
- Returns:
- pandas.CategoricalIndex or pandas.Index
映射后的索引。
参见
Index.map对
Index应用映射关系。Series.map对
Series应用映射关系。Series.apply对
Series应用更复杂的函数。
Examples
>>> 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')