Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เปลี่ยนชื่อหมวดหมู่ใน CategoricalIndex ด้วย rename_categories() ใช้ลิสต์

เมธอด rename_categories() ยังรับลิสต์ของชื่อใหม่ได้ โดยลำดับต้องตรงกับลำดับหมวดหมู่เดิม (categories) ทุกประการ

ตัวอย่างโค้ด

import pandas as pd

catIndex = pd.CategoricalIndex(
    ["p", "q", "r", "s", "p", "q", "r", "s"],
    ordered=True,
    categories=["p", "q", "r", "s"]
)

print("CategoricalIndex เดิม:\n", catIndex)
print("\nหมวดหมู่เดิม:\n", catIndex.categories)

# ใช้ลิสต์เปลี่ยนชื่อหมวดหมู่ตามลำดับ
result = catIndex.rename_categories([5, 10, 15, 20])
print("\nCategoricalIndex หลัง rename_categories(list):\n", result)

ผลลัพธ์

CategoricalIndex เดิม:
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

หมวดหมู่เดิม:
Index(['p', 'q', 'r', 's'], dtype='object')

CategoricalIndex หลัง rename_categories(list):
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')

ลิสต์ [5,10,15,20] แทนที่หมวดหมู่ [p,q,r,s] ตามลำดับ