เมธอด rename_categories() รองรับฟังก์ชัน lambda เพื่อแปลงชื่อหมวดหมู่ทั้งหมดอย่างมีระบบ เช่น แปลงเป็นตัวพิมพ์เล็กทั้งหมด
ตัวอย่างโค้ด
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)
# ใช้ lambda แปลงชื่อหมวดหมู่เป็นตัวพิมพ์เล็ก
result = catIndex.rename_categories(lambda x: x.lower())
print("\nCategoricalIndex หลัง rename_categories(lambda):\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(lambda): CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
หมวดหมู่ P,Q,R,S กลายเป็น p,q,r,s ทั้งหมดโดยอัตโนมัติ