Python Pandas CategoricalIndex - Map values using input correspondence like a dict

To map values using input correspondence like a dictionary, use the CategoricalIndex.map() method in Pandas. This method allows you to transform categorical values by mapping them to new values using a dictionary-like object.

Creating a CategoricalIndex

First, let's create a CategoricalIndex with ordered 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("CategoricalIndex...")
print(catIndex)
CategoricalIndex...
CategoricalIndex(['P', 'Q', 'R', 'S', 'P', 'Q', 'R', 'S'], categories=['P', 'Q', 'R', 'S'], ordered=True, dtype='category')

Mapping Values with Dictionary

Use the map() method to transform categories using a dictionary mapping ?

import pandas as pd

catIndex = pd.CategoricalIndex(["P", "Q", "R", "S", "P", "Q", "R", "S"], 
                               ordered=True, 
                               categories=["P", "Q", "R", "S"])

# Display original categories
print("Original categories:")
print(catIndex.categories)

# Map categories to numeric values
mapping_dict = {'P': 5, 'Q': 10, 'R': 15, 'S': 20}
mapped_index = catIndex.map(mapping_dict)

print("\nCategoricalIndex after mapping:")
print(mapped_index)
Original categories:
Index(['P', 'Q', 'R', 'S'], dtype='object')

CategoricalIndex after mapping:
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')

Key Points

  • The map() method preserves the ordered property of the CategoricalIndex
  • New categories are automatically created based on the mapped values
  • The mapping dictionary must contain all original category values
  • The result maintains the same length and structure as the original index

Conclusion

The CategoricalIndex.map() method provides an efficient way to transform categorical values using dictionary mappings. It preserves the categorical structure while applying the specified transformations to both the data and categories.

Updated on: 2026-03-26T16:56:44+05:30

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements