Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas CategoricalIndex - Đổi tên categories bằng danh sách


Dùng rename_categories() với list categories mới (cùng độ dài, cùng thứ tự với categories cũ).

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. Đổi tên categories bằng list

print("\nCategoricalIndex sau đổi tên (list)...\n", catIndex.rename_categories([5, 10, 15, 20]))

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 đổi tên (list)...\n", catIndex.rename_categories([5, 10, 15, 20]))

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 đổi tên (list)...
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20],
                 categories=[5, 10, 15, 20], ordered=True, dtype='category')

Lưu ý: Danh sách mới phải cùng độ dài với categories cũ. Phần tử thứ i trong list mới thay cho category thứ i trong categories cũ.