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


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

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 with value True −

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

Set the categories to be unordered −

print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())

Example

Following is the code −

import pandas as pd

# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter with value True
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, 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 unordered
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())

Output

This will produce the following output −

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

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

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

Updated on: 18-Oct-2021

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements