Python Pandas 分類索引 - 用 Lambda 重新命名類別


要使用 Lambda 重新命名類別,請在 Pandas 中使用 CategoricalIndex rename_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)

使用 rename_categories() 重新命名類別。設定新類別,使用 lambda 併為所有類別設定小寫 −

print("\nCategoricalIndex after renaming categories...\n",catIndex.rename_categories(lambda a: a.lower()))

示例

以下是程式碼 −

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

# Rename categories using rename_categories()
# Set the new categories that with use lambda and set lowercase for all the categories
print("\nCategoricalIndex after renaming categories...\n",catIndex.rename_categories(lambda a: a.lower()))

輸出

這將產生以下輸出 −

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 renaming categories...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

更新於: 2021 年 10 月 18 日

139 個瀏覽量

職業起飛

完成課程獲得認證

開始學習
廣告
© . All rights reserved.