Python Pandas – 根据基础分类创建索引
要创建基于基础分类的索引,请使用 pandas.CategoricalIndex() 方法。
首先,导入所需的库 −
import pandas as pd
CategoricalIndex是基于基础分类的索引。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)
更多Pandas相关文章,请阅读:Pandas 教程
示例
以下是代码 –
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.min())
# 获取最大值
print("\n从分类索引中获取最大值......\n",catIndex.max())
输出
这将产生以下输出 –
分类索引......
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')
从分类索引中获取最小值......
p
从分类索引中获取最大值......
S
极客教程