Python Pandas CategoricalIndex - 新增新的型別


如要新增新型別,請在 Pandas 中使用 CategoricalIndex add_categories() 方法。首先,匯入必需的庫 −

import pandas as pd

使用 "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)

使用 add_categories() 新增新型別。將新型別作為一個引數設定。新型別將包含在型別中的最後/最高位置 −

print("\nCategoricalIndex after adding new categories...\n",catIndex.add_categories(["a", "b", "c", "d"]))

示例

以下為程式碼 −

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)

# Add new categories using add_categories()
# Set the new categories as a parameter
# The new categories will be included at the last/highest place in the categories
print("\nCategoricalIndex after adding new categories...\n",catIndex.add_categories(["a", "b", "c", "d"]))

輸出

這將生成以下輸出 −

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 adding new categories...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's', 'a', 'b', 'c', 'd'], ordered=True, dtype='category')

更新於: 18-Oct-2021

168 次瀏覽

開啟你的職業生涯

參加並完成課程,獲取認證資格

開始
廣告