- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
Pandas rename_categories() Method
The rename_categories() method allows you to rename categories in a pandas categorical objects, such as Pandas Categorical Series or CategoricalIndex with minimal effort. It supports multiple input types, such as lists, dictionaries, or callable. This method is recommended for renaming categorical data due to its speed, memory efficiency, and semantic benefits.
This is one of the specialized method available in the Pandas Series.cat accessor, an alias for CategoricalAccessor and can also be directly applied to CategoricalIndex. It is particularly useful for handling categorical data by renaming categories for clarity and consistency.
Syntax
Below you can see the syntax of the Python Pandas rename_categories() method, it differs slightly depending on whether you're working with a Categorical Series or a CategoricalIndex object.
Syntax for a Pandas Categorical Series −
Series.cat.rename_categories(new_categories, *args, **kwargs)
Syntax for a CategoricalIndex −
CategoricalIndex.rename_categories(new_categories, *args, **kwargs)
When using the rename_categories() method on a CategoricalIndex, there is no need to use the .cat accessor. This is because the CategoricalIndex is inherently categorical, and methods can be called directly.
Parameters
The Python Pandas rename_categories() method accepts the below parameters −
new_categories − This parameter accepts three types of inputs for renaming categories. It supports three input types: a list-like object, a dictionary, or a callable. When using a list-like input, it specifies a list of new category names where the number of items must match the existing categories length, and all names must be unique. For a dict-like input, it maps old categories to new ones, with categories not included in the mapping remaining unchanged. Alternatively, you can provide a callable function, which dynamically generates new category names by applying the function to each existing category.
**kwargs: Additional key word arguments for customization.
Return Value
The Pandas rename_categories() method returns a new categorical object with renamed categories.
Example: Renaming Categories with a List
Here is a basic example demonstrating renaming categories with a list. Using a list is the simplest way to rename all categories in a Pandas categorical object. For this you should ensure that list length must match the existing categories, and names must be unique.
import pandas as pd
# Creating a categorical Series
s = pd.Series(["a", "b", "c", "a"], dtype="category")
print("Original Series:\n", s)
# Renaming categories using a list
new_categories = ["Group A", "Group B", "Group C"]
s = s.cat.rename_categories(new_categories)
print("\nRenamed Categories:\n", s)
When we run above program, it produces following result −
Original Series: 0 a 1 b 2 c 3 a dtype: category Categories (3, object): ['a', 'b', 'c'] Renamed Categories: 0 Group A 1 Group B 2 Group C 3 Group A dtype: category Categories (3, object): ['Group A', 'Group B', 'Group C']
Example: Renaming categories of a CategoricalIndex object
A CategoricalIndex can only take a limited, fixed set of values. You can use the rename_categories() method to rename categories within such an index. The following example demonstrates the same.
import pandas as pd
# Creating a CategoricalIndex
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
print("CategoricalIndex...\n", catIndex)
# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# Rename categories using a list
print("\nCategoricalIndex after renaming categories...\n", catIndex.rename_categories([5, 10, 15, 20]))
While executing the above code we get the following output −
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') Displaying Categories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex after renaming categories... CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')
Example: Renaming CategoricalIndex with a Dictionary
The following example demonstrates using the rename_categories() method for renaming the categories of a CategoricalIndex object with a dictionary.
import pandas as pd
# Creating a CategoricalIndex
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
print("CategoricalIndex...\n", catIndex)
# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# Rename categories using a dictionary
print("\nCategoricalIndex after renaming categories...\n", catIndex.rename_categories({'p': 5, 'q': 10, 'r': 15, 's': 20}))
Following is an output of the above code −
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') Displaying Categories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex after renaming categories... CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')
Example: Renaming Categories with a Callable
The rename_categories() method can also accepts a callable. This is useful for scenarios where category names need to follow a specific pattern, such as appending prefixes, converting case. The following example transforms all categories to uppercase.
import pandas as pd
# Creating a categorical Series
s = pd.Series(["cat", "dog", "fish", "cat"], dtype="category")
print("Original Series:\n", s)
# Renaming categories using a callable
s = s.cat.rename_categories(lambda x: x.upper())
print("\nRenamed Categories (to uppercase):\n", s)
Following is an output of the above code −
Original Series: 0 cat 1 dog 2 fish 3 cat dtype: category Categories (3, object): ['cat', 'dog', 'fish'] Renamed Categories (to uppercase): 0 CAT 1 DOG 2 FISH 3 CAT dtype: category Categories (3, object): ['CAT', 'DOG', 'FISH']