เมธอด rename_categories() รับ dict mapping เพื่อเปลี่ยนชื่อหมวดหมู่เฉพาะตัวที่ต้องการ คีย์คือชื่อเดิม ค่าคือชื่อใหม่
ตัวอย่างโค้ด
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)
# ใช้ dict mapping เปลี่ยนชื่อหมวดหมู่
result = catIndex.rename_categories({'p': 5, 'q': 10, 'r': 15, 's': 20})
print("\nCategoricalIndex หลัง rename_categories(dict):\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(dict): CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')
หมวดหมู่ p,q,r,s ถูกแปลงเป็นตัวเลข 5,10,15,20 ตาม mapping ที่กำหนด