เมธอด as_ordered() ใช้เปลี่ยน CategoricalIndex ที่ไม่มีลำดับ (ordered=False) ให้มีลำดับ (ordered=True) โดยไม่เปลี่ยนค่าหรือหมวดหมู่
ตัวอย่างโค้ด
import pandas as pd
# สร้าง CategoricalIndex ไม่มีลำดับ
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
categories=["p", "q", "r", "s"]
)
print("CategoricalIndex เดิม:\n", catIndex)
print("\nหมวดหมู่:\n", catIndex.categories)
# ตั้งค่าให้มีลำดับ
ordered_index = catIndex.as_ordered()
print("\nCategoricalIndex หลัง as_ordered():\n", ordered_index)
ผลลัพธ์
CategoricalIndex เดิม: CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category') หมวดหมู่: Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex หลัง as_ordered(): CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
เปลี่ยนจาก ordered=False เป็น ordered=True ค่าและหมวดหมู่ไม่เปลี่ยน