當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python pandas.CategoricalIndex.map用法及代碼示例

用法:

CategoricalIndex.map(mapper)

使用輸入映射或函數映射值。

將索引的值(它們的類別,而不是代碼)映射到新類別。如果映射對應關係是one-to-one,則結果是CategoricalIndex,它具有與原始相同的順序屬性,否則返回Index

如果使用 dictSeries ,則任何未映射的類別都將映射到 NaN 。請注意,如果發生這種情況,將返回 Index

參數

mapper函數、字典或係列

映射對應。

返回

pandas.CategoricalIndex 或 pandas.Index

映射索引。

例子

>>> 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')

如果映射是one-to-one,則保留類別的順序:

>>> 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')

如果映射不是one-to-one,則返回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')

相關用法


注:本文由純淨天空篩選整理自pandas.pydata.org大神的英文原創作品 pandas.CategoricalIndex.map。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。