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

Python Pandas - Lấy giá trị lớn nhất từ Ordered CategoricalIndex

Để lấy giá trị lớn nhất từ Ordered CategoricalIndex, sử dụng phương thức catIndex.max() trong Pandas.

Trước tiên, import thư viện cần thiết:

import pandas as pd

Thiết lập danh mục cho categorical bằng tham số categories. Xử lý categorical theo thứ tự bằng tham số ordered:

catIndex = pd.CategoricalIndex(
    ["p", "q", "r", "s", "p", "q", "r", "s"],
    ordered=True,
    categories=["p", "q", "r", "s"]
)

Hiển thị Categorical Index:

print("Categorical Index...\n", catIndex)

Lấy giá trị lớn nhất:

print("\nGiá trị lớn nhất từ CategoricalIndex...\n", catIndex.max())

Ví dụ hoàn chỉnh

import pandas as pd

# CategoricalIndex chỉ nhận số lượng hữu hạn các giá trị có thể
# Thiết lập danh mục bằng tham số "categories"
# Xử lý theo thứ tự bằng tham số "ordered"
catIndex = pd.CategoricalIndex(
    ["p", "q", "r", "s", "p", "q", "r", "s"],
    ordered=True,
    categories=["p", "q", "r", "s"]
)

# Hiển thị Categorical Index
print("Categorical Index...\n", catIndex)

# Lấy các danh mục
print("\nHiển thị danh mục từ CategoricalIndex...\n", catIndex.categories)

# Lấy giá trị lớn nhất
print("\nGiá trị lớn nhất từ CategoricalIndex...\n", catIndex.max())

Kết quả đầu ra

Categorical Index... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
Hiển thị danh mục từ CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object')
Giá trị lớn nhất từ CategoricalIndex... s