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

Python Pandas - Lấy giá trị nhỏ nhất từ Ordered CategoricalIndex

Để lấy giá trị nhỏ nhất từ Ordered CategoricalIndex, sử dụng phương thức catIndex.min() 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ị nhỏ nhất:

print("\nGiá trị nhỏ nhất từ CategoricalIndex...\n", catIndex.min())

Ví dụ hoàn chỉnh

import pandas as pd

# CategoricalIndex là Index dựa trên Categorical nền
# 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ị nhỏ nhất
print("\nGiá trị nhỏ nhất từ CategoricalIndex...\n", catIndex.min())

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ị nhỏ nhất từ CategoricalIndex... p