Pandas reorder_categories() Method



The reorder_categories() method in Pandas is designed for rearranging the categories of a categorical object. This method ensures that all old categories are included, and no new categories are introduced. It is useful when you need to redefine the logical order of categorical data.

This method belongs to Pandas Series.cat accessor (CategoricalAccessor) and can be applied to both Categorical Series or CategoricalIndex objects. This functionality is particularly helpful when sorting or performing ordered comparisons on categorical data.

Syntax

The reorder_categories() method can be used differently depending on whether it's applied to a Categorical Series or a CategoricalIndex object.

Syntax for a Pandas Categorical Series −

Series.cat.reorder_categories(new_categories, ordered, *args, **kwargs)

Syntax for a CategoricalIndex −

CategoricalIndex.reorder_categories(new_categories, ordered, *args, **kwargs)

Parameters

The Python Pandas reorder_categories() method accepts the following parameters −

  • new_categories: A list-like object specifying the new category order. All original categories must be included without introducing new ones.

  • ordered: If specified, sets whether the categorical data should be treated as ordered. If not provided, the existing ordered status remains unchanged.

  • **kwargs: Additional keyword arguments for customization.

Return Value

The Pandas reorder_categories() method returns a Categorical Series or CategoricalIndex object with updated category order.

Exception

This method will raise a ValueError if new_categories fails to include all old categories or introduces new ones.

Example: Reordering Categories in a Pandas Series

The following example demonstrates how to reorder categories in a Pandas Series using the Series.cat.reorder_categories() method.

import pandas as pd

# Create a Categorical Series
s = pd.Series([1, 2, 3, 1], dtype="category")

# Reorder the categories
s = s.cat.reorder_categories([2, 3, 1], ordered=True)

# Display the reordered series
print(s)

When we run above program, it produces following result −

Original Series:
0    1
1    2
2    3
3    1
dtype: category
Categories (3, int64): [1, 2, 3]

Series after reordering categories:
0    1
1    2
2    3
3    1
dtype: category
Categories (3, int64): [2 

Example: Reordering Categories of a CategoricalIndex

The following example demonstrates using the Pandas reorder_categories() method for reordering the categories of a CategoricalIndex object.

import pandas as pd

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

print("Original CategoricalIndex:")
print(catIndex)

# Reorder categories
catIndex = catIndex.reorder_categories(["r", "s", "q", "p"], ordered=True)

print("\nCategoricalIndex after reordering categories:")
print(catIndex)

While executing the above code we get the following output −

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

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

Example: Handling Exceptions When reordering Categories

This example demonstrates the behavior of the reorder_categories() method when you try to reorder with incorrect new_categories list.

import pandas as pd

# Create a categorical Series
s = pd.Series(['red', 'green', 'blue'], dtype='category')

# Dispaly the Input Series
print("Original Series:")
print(s)

# Attempt to reorder categories with an incorrect list
try:
    s = s.cat.reorder_categories(['red', 'blue', 'yellow'], ordered=True)
except ValueError as e:
    print("\nError occurred:", e)

Following is an output of the above code −

Original Series:
0      red
1    green
2     blue
dtype: category
Categories (3, object): ['blue', 'green', 'red']

Error occurred: items in new_categories are not the same as in old categories
python_pandas_reordering_categories.htm
Advertisements