Python Pandas CategoricalIndex – 重命名类别
若要重命名类别,请使用Pandas中的CategoricalIndex rename_categories() 方法。首先,导入所需的库 −
import pandas as pd
CategoricalIndex 只能拥有有限且通常是固定的可能值的数量。使用“categories”参数为分类设置类别。使用“ordered”参数将分类视为有序 −
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
重命名类别。设置将替换旧类别的新类别 −
print("\n重命名类别后的分类索引...\n",catIndex.rename_categories([5, 10, 15, 20]))
例子
以下是代码 −
import pandas as pd
# CategoricalIndex 只能拥有有限且通常是固定的可能值的数量
# 使用“categories”参数为分类设置类别
# 使用“ordered”参数将分类视为有序
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
# 显示分类索引
print("分类索引...\n",catIndex)
# 获取类别
print("\n从分类索引中显示类别...\n",catIndex.categories)
# 重命名类别
# 设置将替换旧类别的新类别
print("\n重命名类别后的分类索引...\n",catIndex.rename_categories([5, 10, 15, 20]))
输出
将生成以下输出 −
分类索引...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
从分类索引中显示类别...
Index(['p', 'q', 'r', 's'], dtype='object')
重命名类别后的分类索引...
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')
极客教程