Python Pandas - 从有序类别索引中获取最大值


要从有序类别索引中获取最大值,请在 Pandas 中使用 catIndex.max() 方法。

首先,导入必需的库 −

import pandas as pd

使用“categories”参数设置类别类别的,使用“ordered”参数将类别视为有序类别 −

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

显示类别索引 −

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

获取最大值 −

print("\nMaximum value from CategoricalIndex...\n",catIndex.max())

示例

以下是代码 −

import pandas as pd

# CategoricalIndex can only take on a limited, and usually fixed, number of possible values.
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
catIndex = pd.CategoricalIndex(
   ["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"]
)

# Display the Categorical Index
print("Categorical Index...\n",catIndex)

# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)

# Get the max value
print("\nMaximum value from CategoricalIndex...\n",catIndex.max())

输出

将生成以下输出 −

Categorical Index...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

Displaying Categories from CategoricalIndex...
Index(['p', 'q', 'r', 's'], dtype='object')

Maximum value from CategoricalIndex...
S

更新于: 2021-10-14

349 次浏览

开启您的 职业生涯

完成课程并获得认证

开始
广告