Python Pandas CategoricalIndex - 获取此分类的类别


要获取此分类的类别,请使用 Pandas 中 CategoricalIndexcategories 属性。首先,导入所需的库 −

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("Categorical Index...\n",catIndex)

获取类别 −

print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)

范例

如下所示为代码 −

import pandas as pd

# CategoricalIndex can only take on a limited, and usually fixed, number of possible values
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

# Display the Categorical Index
print("Categorical Index...\n",catIndex)

# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)

输出

将产生以下输出 −

Categorical Index...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

DisplayingCategories from CategoricalIndex...
Index(['p', 'q', 'r', 's'], dtype='object')

更新于:2021 年 10 月 18 日

381 次浏览

启动您的职业生涯

完成课程即可获得认证

开始
广告