Python Pandas CategoricalIndex - 獲取此分類的類別程式碼


若要獲取此分類的類別程式碼,請在 Pandas 中使用 CategoricalIndexcodes 屬性。首先,匯入所需的庫 −

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("\nCategory codes from CategoricalIndex...\n",catIndex.codes)

示例

以下為程式碼 −

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
# Codes are an array of integers which are the positions of the actual values in the categories array.
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("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

# Get the category codes
print("\nCategory codes from CategoricalIndex...\n",catIndex.codes)

輸出

這將產生以下輸出 −

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

Category codes from CategoricalIndex...
[0 1 2 3 0 1 2 3]

更新於:18-Oct-2021

306 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.