Python Pandas CategoricalIndex - 使用类似字典的输入对应关系映射值
pythonserver side programmingprogramming更新于 2026/1/12 0:44:17
要使用类似字典的输入对应关系映射值,请使用 Pandas 中的 CategoricalIndex.map() 方法。首先,导入所需的库 −
import pandas as pd
使用 "categories" 参数设置分类的类别。使用 "ordered" 将分类视为有序的参数 −
catIndex = pd.CategoricalIndex(["P", "Q", "R", "S","P", "Q", "R", "S"], ordered=True, categories=["P", "Q", "R", "S"])
显示 CategoricalIndex −
print("CategoricalIndex...\n",catIndex)
映射类别 −
print("\n映射后的分类索引...\n",catIndex.map({'P': 5, 'Q': 10, 'R': 15, 'S': 20}))
示例
以下是代码 −
import pandas as pd
# 使用"categories"参数设置分类的类别
# 使用"ordered"将分类视为有序的参数
catIndex = pd.CategoricalIndex(["P", "Q", "R", "S","P", "Q", "R", "S"], ordered=True, categories=["P", "Q", "R", "S"])
# 显示 CategoricalIndex
print("CategoricalIndex...\n",catIndex)
# 获取类别
print("\n显示来自 CategoricalIndex 的类别...\n",catIndex.categories)
# 映射类别
print("\n映射后的 CategoricalIndex...\n",catIndex.map({'P': 5, 'Q': 10, 'R': 15, 'S': 20}))
输出
这将产生以下输出 −
CategoricalIndex... CategoricalIndex(['P', 'Q', 'R', 'S', 'P', 'Q', 'R', 'S'], categories=['P', 'Q', 'R', 'S'], ordered=True, dtype='category') 显示来自 CategoricalIndex 的类别... Index(['P', 'Q', 'R', 'S'], dtype='object') 映射后的 CategoricalIndex... CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

