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

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


Dùng phương thức rename_categories() với hàm lambda đổi tên tất cả categories theo quy tắc (ví dụ: viết thường).

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 lambda

print("\nCategoricalIndex sau đổi tên (lowercase)...\n", catIndex.rename_categories(lambda x: x.lower()))

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 (lowercase)...\n", catIndex.rename_categories(lambda x: x.lower()))

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

Lưu ý: Hàm lambda nhận mỗi category cũ, trả về category mới. Phải trả về giá trị duy nhất cho mỗi đầu vào.