Dùng phương thức reorder_categories() sắp xếp lại thứ tự categories trong CategoricalIndex (chỉ đổi thứ tự, không đổi giá trị).
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo CategoricalIndex
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True, categories=["p", "q", "r", "s"])
3. Hiển thị CategoricalIndex
print("CategoricalIndex...\n", catIndex)
4. Sắp xếp lại categories
print("\nCategoricalIndex sau sắp xếp lại...\n", catIndex.reorder_categories(["r", "s", "q", "p"]))
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 sau sắp xếp lại...\n", catIndex.reorder_categories(["r", "s", "q", "p"]))
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 sau sắp xếp lại...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')
Lưu ý: Giá trị phần tử không đổi, chỉ thay đổi thứ tự so sánh. Danh sách categories mới phải là hoán vị của categories cũ (không thiếu, không dư).