- 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 reorder_categories() Method
The reorder_categories() method in Pandas is designed for rearranging the categories of a categorical object. This method ensures that all old categories are included, and no new categories are introduced. It is useful when you need to redefine the logical order of categorical data.
This method belongs to Pandas Series.cat accessor (CategoricalAccessor) and can be applied to both Categorical Series or CategoricalIndex objects. This functionality is particularly helpful when sorting or performing ordered comparisons on categorical data.
Syntax
The reorder_categories() method can be used differently depending on whether it's applied to a Categorical Series or a CategoricalIndex object.
Syntax for a Pandas Categorical Series −
Series.cat.reorder_categories(new_categories, ordered, *args, **kwargs)
Syntax for a CategoricalIndex −
CategoricalIndex.reorder_categories(new_categories, ordered, *args, **kwargs)
Parameters
The Python Pandas reorder_categories() method accepts the following parameters −
new_categories: A list-like object specifying the new category order. All original categories must be included without introducing new ones.
ordered: If specified, sets whether the categorical data should be treated as ordered. If not provided, the existing ordered status remains unchanged.
**kwargs: Additional keyword arguments for customization.
Return Value
The Pandas reorder_categories() method returns a Categorical Series or CategoricalIndex object with updated category order.
Exception
This method will raise a ValueError if new_categories fails to include all old categories or introduces new ones.
Example: Reordering Categories in a Pandas Series
The following example demonstrates how to reorder categories in a Pandas Series using the Series.cat.reorder_categories() method.
import pandas as pd # Create a Categorical Series s = pd.Series([1, 2, 3, 1], dtype="category") # Reorder the categories s = s.cat.reorder_categories([2, 3, 1], ordered=True) # Display the reordered series print(s)
When we run above program, it produces following result −
Original Series: 0 1 1 2 2 3 3 1 dtype: category Categories (3, int64): [1, 2, 3] Series after reordering categories: 0 1 1 2 2 3 3 1 dtype: category Categories (3, int64): [2Example: Reordering Categories of a CategoricalIndex
The following example demonstrates using the Pandas reorder_categories() method for reordering the categories of a CategoricalIndex object.
import pandas as pd # Create a CategoricalIndex catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"]) print("Original CategoricalIndex:") print(catIndex) # Reorder categories catIndex = catIndex.reorder_categories(["r", "s", "q", "p"], ordered=True) print("\nCategoricalIndex after reordering categories:") print(catIndex)While executing the above code we get the following output −
Original CategoricalIndex: CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') CategoricalIndex after reordering categories: CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')Example: Handling Exceptions When reordering Categories
This example demonstrates the behavior of the reorder_categories() method when you try to reorder with incorrect new_categories list.
import pandas as pd # Create a categorical Series s = pd.Series(['red', 'green', 'blue'], dtype='category') # Dispaly the Input Series print("Original Series:") print(s) # Attempt to reorder categories with an incorrect list try: s = s.cat.reorder_categories(['red', 'blue', 'yellow'], ordered=True) except ValueError as e: print("\nError occurred:", e)Following is an output of the above code −
Original Series: 0 red 1 green 2 blue dtype: category Categories (3, object): ['blue', 'green', 'red'] Error occurred: items in new_categories are not the same as in old categoriespython_pandas_reordering_categories.htm