Python Pandas 分类索引 - 重新排序类别


为了重新排序类别,在 Pandas 中使用 CategoricalIndex 的 reorder_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"])

显示 CategoricalIndex -

print("CategoricalIndex...\n",catIndex)

获取类别 -

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

使用 reorder_categories() 重新排序类别。将类别按新顺序作为参数设置 -

print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"]))

示例

以下是代码 -

import pandas as pd

# CategoricalIndex can only take on a limited,and usually fixed, number of possible values (categories
# 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 CategoricalIndex
print("CategoricalIndex...\n",catIndex)

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

# Reorder categories using reorder_categories()
# Set the categories in new order as a parameter
print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"]))

输出

这将产生以下输出 -

CategoricalIndex...
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')

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

更新于: 18-Oct-2021

368 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.