Python Pandas - Set the categories of the CategoricalIndex to be ordered

PythonServer Side ProgrammingProgramming

To set the categories of the CategoricalIndex to be ordered, use the as_ordered() method in Pandas.

At first, import the required libraries −

import pandas as pd

Set the categories for the categorical using the "categories" parameter −

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

Get the categories −

print("
Displaying Categories from CategoricalIndex...
",catIndex.categories)

Set the categories to be ordered −

print("
CategoricalIndex ordered...
", catIndex.as_ordered())

Example

Following is the code −

import pandas as pd

# Set the categories for the categorical using the "categories" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], categories=["p", "q", "r", "s"])

# Display the CategoricalIndex
print("CategoricalIndex...
",catIndex) # Get the categories print("
Displaying Categories from CategoricalIndex...
",catIndex.categories) # Set the categories to be ordered print("
CategoricalIndex ordered...
", catIndex.as_ordered())

Output

This will produce the following output −

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

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

CategoricalIndex ordered...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
raja
Updated on 18-Oct-2021 07:15:46

Advertisements