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

PythonServer Side ProgrammingProgramming

To Map values using input correspondence like a dict, use the CategoricalIndex.map() 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 −

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)

Map categories −

print("\nCategoricalIndex after mapping...\n",catIndex.map({'P': 5, 'Q': 10, 'R': 15, 'S': 20}))

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

# Map categories
print("\nCategoricalIndex after mapping...\n",catIndex.map({'P': 5, 'Q': 10, 'R': 15, 'S': 20}))

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 mapping...
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')
raja
Updated on 18-Oct-2021 07:18:29

Advertisements