Skip to content

Pandas Categorical Rename Quick Fix

DodaTech Updated 2026-06-26 2 min read

You will learn how to rename categories in a pandas categorical column using .cat.rename_categories() and avoid common pitfalls that cause data corruption.

The Problem

When you need to update category labels -- for example, renaming "Male"/"Female" to "M"/"F" or translating categories -- doing a find-and-replace on the raw column is slow, risky, and breaks the categorical encoding.

The Wrong Way

import pandas as pd
s = pd.Series(["good", "bad", "good", "ugly"], dtype="category")
s[s == "bad"] = "poor"
print(s)

Output:

0    good
1    poor
2    good
3    ugly
dtype: category
Categories (3, object): ['bad', 'good', 'ugly']

The category bad still exists in the list even though no values use it, and poor was silently added as a value instead of replacing the category.

The Right Way

s = pd.Series(["good", "bad", "good", "ugly"], dtype="category")
s = s.cat.rename_categories({"bad": "poor", "good": "excellent", "ugly": "terrible"})
print(s)
print(s.cat.categories)

Output:

0    excellent
1         poor
2    excellent
3     terrible
dtype: category
Categories (3, object): ['poor', 'excellent', 'terrible']

All categories are renamed cleanly with no stale entries.

Step-by-Step Fix

1. Prepare your mapping dict

rename_map = {"old_name": "new_name", ...}

2. Call rename_categories with the dict

s = s.cat.rename_categories(rename_map)

3. (Optional) Rename with a callable

s = s.cat.rename_categories(str.upper)

Prevention Tips

  • Use .cat.rename_categories() instead of element-wise replacement on categorical columns
  • Pass a dict mapping old category to new category for precision
  • Use a callable (like str.title) for bulk transformations
  • Verify with .cat.categories after renaming

Common Mistakes

  1. Using str.replace() or .replace() on the Series instead of renaming categories -- breaks the categorical dtype
  2. Not updating all categories in the mapping dict -- causes a ValueError for missing keys
  3. Assuming rename is in-place -- returns a new Series; reassign the result

These mistakes appear frequently in real-world pandas code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

FAQ

### Does `rename_categories` change the underlying codes?

No. Only the category labels change; the integer codes remain the same.

Can I rename with a partial mapping?

No, the dict must include every existing category. Use add_categories and remove_categories instead for partial changes.

What happens to order after renaming?

Category order is preserved; only the labels change.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tools integrate seamlessly with pandas for enhanced productivity and security.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro