Python Pandas CategoricalIndex - Reorder categories


To eorder categories, use the CategoricalIndex reorder_categories() method in Pandas. At first, import the required libraries −

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 CategoricalIndex −

print("CategoricalIndex...\n",catIndex)

Get the categories −

print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

Reorder categories using reorder_categories(). Set the categories in new order as a parameter −

print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"]))

Example

Following is the code −

import pandas as pd

# CategoricalIndex can only take on a limited,and usually fixed, number of possible values (categories
# 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 CategoricalIndex
print("CategoricalIndex...\n",catIndex)

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

# Reorder categories using reorder_categories()
# Set the categories in new order as a parameter
print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"]))

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

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

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

Updated on: 18-Oct-2021

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements