เมธอด map() ของ CategoricalIndex ใช้แปลงค่าของแต่ละหมวดหมู่ตาม mapping ที่กำหนด (dict) ผลลัพธ์จะเป็น CategoricalIndex ใหม่ที่มีหมวดหมู่เป็นค่าที่แมปแล้ว
ตัวอย่างโค้ด
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)
# แมปค่าหมวดหมู่ใหม่
mapped = catIndex.map({'P': 5, 'Q': 10, 'R': 15, 'S': 20})
print("\nCategoricalIndex หลังแมป:\n", mapped)
ผลลัพธ์
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 หลังแมป: 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 ตามลำดับ คงลำดับ ordered ไว้