Python Pandas – 将CategoricalIndex的类别设置为有序

Python Pandas – 将CategoricalIndex的类别设置为有序

要将CategoricalIndex的类别设置为有序,请使用Pandas中的 as_ordered() 方法。

首先,导入所需的库 −

import pandas as pd

使用“categories”参数设置分类的类别−

catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], categories=["p", "q", "r", "s"])

获取类别 −

print("\n从CategoricalIndex中显示类别...\n",catIndex.categories)

将类别设置为有序 −

print("\nCategoricalIndex有序...\n", catIndex.as_ordered())

示例代码

以下是代码 −

import pandas as pd

# 使用“categories”参数设置分类的类别
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], categories=["p", "q", "r", "s"])

# 显示CategoricalIndex
print("CategoricalIndex...\n",catIndex)

# 获取类别
print("\n从CategoricalIndex中显示类别...\n",catIndex.categories)

# 将类别设置为有序
print("\nCategoricalIndex有序...\n", catIndex.as_ordered())

输出

这将产生以下输出 −

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

从CategoricalIndex中显示类别...
Index(['p', 'q', 'r', 's'], dtype='object')

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程