Dùng phương thức as_ordered() chuyển CategoricalIndex từ unordered sang ordered (có thứ tự so sánh).
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo CategoricalIndex unordered
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
categories=["p", "q", "r", "s"])
3. Hiển thị categories
print("\nCategories...\n", catIndex.categories)
4. Đặt thành ordered
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered())
Ví dụ hoàn chỉnh
import pandas as pd
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
categories=["p", "q", "r", "s"])
print("CategoricalIndex...\n", catIndex)
print("\nCategories...\n", catIndex.categories)
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered())
Kết quả đầu ra
CategoricalIndex...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
categories=['p', 'q', 'r', 's'], ordered=False, dtype='category')
Categories...
Index(['p', 'q', 'r', 's'], dtype='object')
CategoricalIndex ordered...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
Lưu ý: Khi ordered=True, các phép so sánh (<, >, <=, >=) giữa các phần tử được phép thực hiện theo thứ tự categories.