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


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("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)

Set the categories to be ordered −

print("\nCategoricalIndex ordered...\n", 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...\n",catIndex)

# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)

# Set the categories to be ordered
print("\nCategoricalIndex ordered...\n", 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')

Updated on: 18-Oct-2021

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements