Python Pandas - Get the maximum value from Ordered CategoricalIndex

PythonPandasServer Side ProgrammingProgramming

To get the maximum value from Ordered CategoricalIndex, use the catIndex.max() method in Pandas.

At first, import the required libraries −

import pandas as pd

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 max value −

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

Example

Following is the code −

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())

Output

This will produce the following output −

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
raja
Published on 14-Oct-2021 11:11:50
Advertisements