Dùng phương thức as_unordered() chuyển CategoricalIndex từ ordered sang unordered (không so sánh được).
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo CategoricalIndex ordered
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True, categories=["p", "q", "r", "s"])
3. Đặt thành unordered
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())
Ví dụ hoàn chỉnh
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("\nCategories...\n", catIndex.categories)
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())
Kết quả đầu ra
CategoricalIndex...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
Categories...
Index(['p', 'q', 'r', 's'], dtype='object')
CategoricalIndex unordered...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
categories=['p', 'q', 'r', 's'], ordered=False, dtype='category')
Lưu ý: as_unordered() và as_ordered() trả về CategoricalIndex mới, không sửa đổi inplace.