Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - Get the maximum value from Ordered CategoricalIndex
To get the maximum value from an Ordered CategoricalIndex, use the catIndex.max() method in Pandas. The maximum value is determined by the order of categories, not alphabetical sorting.
Creating an Ordered CategoricalIndex
First, import the required libraries and create a CategoricalIndex with ordered categories ?
import pandas as pd
# Create an ordered CategoricalIndex
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
print("Categorical Index...")
print(catIndex)
Categorical Index... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
Getting the Maximum Value
Use the max() method to get the maximum value based on the category order ?
import pandas as pd
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
print("Categories:")
print(catIndex.categories)
print("\nMaximum value from CategoricalIndex:")
print(catIndex.max())
Categories: Index(['p', 'q', 'r', 's'], dtype='object') Maximum value from CategoricalIndex: s
How It Works
In an ordered CategoricalIndex, the maximum value is the last category in the defined order, regardless of alphabetical order. Since we defined categories as ["p", "q", "r", "s"], "s" is the maximum value.
Example with Different Category Order
import pandas as pd
# Different category order
catIndex2 = pd.CategoricalIndex(
["p", "q", "r", "s"],
ordered=True,
categories=["s", "r", "q", "p"] # Different order
)
print("CategoricalIndex with different order:")
print(catIndex2)
print("\nMaximum value:")
print(catIndex2.max())
CategoricalIndex with different order: CategoricalIndex(['p', 'q', 'r', 's'], categories=['s', 'r', 'q', 'p'], ordered=True, dtype='category') Maximum value: p
Key Points
- The
ordered=Trueparameter is required formax()to work - Maximum value is determined by category order, not alphabetical order
- The last category in the
categorieslist is considered the maximum
Conclusion
Use catIndex.max() to get the maximum value from an ordered CategoricalIndex. The result depends on the category order defined during creation, not alphabetical sorting.
