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

Python Pandas CategoricalIndex - Thêm categories mới


Dùng phương thức add_categories() thêm categories mới vào CategoricalIndex. Categories mới được thêm vào cuối (vị trí cao nhất).

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. Thêm categories mới

print("\nCategoricalIndex sau thêm a,b,c,d...\n", catIndex.add_categories(["a", "b", "c", "d"]))

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 thêm a,b,c,d...\n", catIndex.add_categories(["a", "b", "c", "d"]))

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 thêm a,b,c,d...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
                 categories=['p', 'q', 'r', 's', 'a', 'b', 'c', 'd'], ordered=True, dtype='category')

Lưu ý: add_categories() không thay đổi giá trị hiện tại, chỉ mở rộng tập categories. Categories mới ở cuối → lớn hơn categories cũ khi ordered=True.