Python Pandas - 基於底層分類建立索引


要基於底層分類建立索引,請使用 **pandas.CategoricalIndex()** 方法。

首先,匯入所需的庫 −

import pandas as pd

CategoricalIndex 是基於底層分類的索引。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("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

示例

以下是程式碼 −

import pandas as pd

# CategoricalIndex is the Index based on an underlying Categorical
# 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("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

# Get the min value
print("\nMinimum value from CategoricalIndex...\n",catIndex.min())

# Get the max value
print("\nMaximum value from CategoricalIndex...\n",catIndex.max())

輸出

這將產生以下輸出 −

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

Minimum value from CategoricalIndex...
p

Maximum value from CategoricalIndex...
S

更新於: 14-10-2021

459 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

開始學習
廣告