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

Python Pandas CategoricalIndex - Ánh xạ giá trị bằng dict


Dùng phương thức CategoricalIndex.map() ánh xạ từng category sang giá trị mới theo dict.

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. Ánh xạ categories

print("\nCategoricalIndex sau map...\n", catIndex.map({'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 map...\n", catIndex.map({'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 map...
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20],
                 categories=[5, 10, 15, 20], ordered=True, dtype='category')

Lưu ý: map() trả về CategoricalIndex mới với categories đã được biến đổi. Dict phải bao phủ tất cả categories hiện tại.