เมธอด reorder_categories() ใช้เปลี่ยนลำดับของหมวดหมู่ใน 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)
# จัดเรียงลำดับหมวดหมู่ใหม่
result = catIndex.reorder_categories(["r", "s", "q", "p"])
print("\nCategoricalIndex หลัง reorder_categories():\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 หลัง reorder_categories(): CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')
ลำดับหมวดหมู่เปลี่ยนเป็น r, s, q, p ค่าในดัชนียังคงเป็น p,q,r,s แต่ความหมายของลำดับเปลี่ยนไป