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

Python Pandas CategoricalIndex - Đổi tên categories bằng dict


Dùng rename_categories() với dict ánh xạ từng category cũ sang category mới cụ thể.

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 dict

print("\nCategoricalIndex sau đổi tên (dict)...\n", catIndex.rename_categories({'p': 5, 'q': 10, 'r': 15, 's': 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 (dict)...\n", catIndex.rename_categories({'p': 5, 'q': 10, 'r': 15, 's': 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 (dict)...
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20],
                 categories=[5, 10, 15, 20], ordered=True, dtype='category')

Lưu ý: Dict phải có key cho tất cả categories hiện tại. Thứ tự categories mới theo thứ tự dict (Python 3.7+ giữ thứ tự insertion).