Python Pandas CategoricalIndex - Add new categories

To add new categories to a Pandas CategoricalIndex, use the add_categories() method. This method extends the available categories without changing the existing data values.

Creating a CategoricalIndex

First, let's create a CategoricalIndex with initial categories ?

import pandas as pd

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

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

Viewing Current Categories

Check the existing categories before adding new ones ?

import pandas as pd

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

print("Current categories:")
print(catIndex.categories)
Current categories:
Index(['p', 'q', 'r', 's'], dtype='object')

Adding New Categories

Use add_categories() to append new categories to the end of the category list ?

import pandas as pd

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

# Add new categories
expanded_catIndex = catIndex.add_categories(["a", "b", "c", "d"])

print("CategoricalIndex after adding new categories:")
print(expanded_catIndex)
print("\nNew categories list:")
print(expanded_catIndex.categories)
CategoricalIndex after adding new categories:
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's', 'a', 'b', 'c', 'd'], ordered=True, dtype='category')

New categories list:
Index(['p', 'q', 'r', 's', 'a', 'b', 'c', 'd'], dtype='object')

Key Points

Feature Description
Method add_categories()
Position New categories added at the end
Original Data Unchanged - only category list expands
Order Preserved Yes, for ordered CategoricalIndex

Conclusion

The add_categories() method expands the available categories without modifying existing data values. New categories are appended to the end of the category list, preserving the original order for ordered CategoricalIndex objects.

Updated on: 2026-03-26T16:55:58+05:30

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements