Python Pandas CategoricalIndex - Check whether the categories have an ordered relationship

PythonServer Side ProgrammingProgramming

To check whether the categories have an ordered relationship, use the ordered property of the CategoricalIndex.

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...
",catIndex)

Get the categories −

print("
DisplayingCategories from CategoricalIndex...
",catIndex.categories)

Check categories for ordered relationship −

print("
Does categories have ordered relationship...
",catIndex.ordered)

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...
",catIndex) # Get the categories print("
DisplayingCategories from CategoricalIndex...
",catIndex.categories) # Check categories for ordered relationship print("
Does categories have ordered relationship...
",catIndex.ordered)

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

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

Does categories have ordered relationship...
True
raja
Updated on 18-Oct-2021 06:44:28

Advertisements