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

Python Pandas - Xóa categories chỉ định khỏi CategoricalIndex


Dùng phương thức remove_categories() xóa một hoặc nhiều categories khỏi CategoricalIndex. Giá trị thuộc category bị xóa sẽ thành NaN.

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. Xóa categories 'p' và 'q'

print("\nCategoricalIndex sau xóa p,q...\n", catIndex.remove_categories(["p", "q"]))

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 xóa p,q...\n", catIndex.remove_categories(["p", "q"]))

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 xóa p,q...
CategoricalIndex([nan, nan, 'r', 's', nan, nan, 'r', 's'],
                 categories=['r', 's'], ordered=True, dtype='category')

Lưu ý: Phần tử bị xóa category → thành NaN. Categories còn lại giữ nguyên thứ tự. Dùng add_categories() để thêm ngược lại.