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 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告