- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas CategoricalIndex - Map values using input correspondence like a dict
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')
Advertisements