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 minimum value from Ordered CategoricalIndex
To get the minimum value from an Ordered CategoricalIndex, use the catIndex.min() method in Pandas. This method returns the first category in the ordered sequence, not the alphabetically smallest value.
Creating an Ordered CategoricalIndex
First, let's 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 Minimum Value
Use the min() method to get the minimum value from the ordered categorical ?
import pandas as pd
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
print("Categories:", catIndex.categories)
print("Minimum value:", catIndex.min())
Categories: Index(['p', 'q', 'r', 's'], dtype='object') Minimum value: p
How It Works
The min() method returns the first category in the ordered sequence, which is "p" in this case. The order is determined by the categories parameter, not alphabetical order.
Example with Different Category Order
Let's see what happens when we change the category order ?
import pandas as pd
# Different category order
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["s", "r", "q", "p"] # Different order
)
print("Categories:", catIndex.categories)
print("Minimum value:", catIndex.min())
Categories: Index(['s', 'r', 'q', 'p'], dtype='object') Minimum value: s
Conclusion
The min() method on an ordered CategoricalIndex returns the first category in the defined order, not the alphabetically smallest value. This makes it useful for working with ordinal data like ratings or grades.
