Sub topic 6
Managing categories safely
A categorical column keeps a fixed list of allowed values, called categories. Changing that list is different from changing ordinary data, and a careless change can silently turn values into missing values or break an ordering. This chapter covers the .cat methods that edit categories, how each one behaves, and which mistakes to avoid.
This chapter assumes you can create a categorical with astype("category") or pd.CategoricalDtype. It also assumes you know that each row stores an integer code that points into the categories, and that you can read a Series and a DataFrame. The examples target pandas 2.x.
Why categories are not free-form
An object column accepts any value. A categorical column accepts only values that appear in its categories, or missing values. Assigning anything else fails.
import pandas as pd
s = pd.Series(["a", "b", "a"], dtype="category")
try:
s.iloc[1] = "z"
except (TypeError, ValueError) as err:
print("rejected:", type(err).__name__)
print(s.tolist())pandas 2.x raises TypeError here, and older versions raise ValueError, so the example catches both. The assignment is rejected because "z" has no integer code. The failure is deliberate. Without it, a typo such as "z" for "a" would quietly add a new category.
To accept a new value, change the category list first, then assign.
The editing methods
Every method below lives on the .cat accessor. In pandas 2.x they return a new object and never modify the original, so you must assign the result back.
| Method | What it does | Typical failure |
|---|---|---|
| `add_categories(new)` | Appends categories that are not yet present | `ValueError` if a category already exists |
| `remove_categories(old)` | Deletes categories. Rows that used them become missing | `ValueError` if a category is not present |
| `remove_unused_categories()` | Deletes every category that no row uses | None |
| `rename_categories(x)` | Changes labels, using a list, a dict, or a function | `ValueError` if the result has duplicate labels |
| `reorder_categories(new, ordered=...)` | Changes the order of the same set of categories | `ValueError` if the set of categories differs |
| `set_categories(new, ordered=...)` | Replaces the category list. Values not in it become missing | None, but data can be lost silently |
| `as_ordered()` / `as_unordered()` | Switches the ordered flag without touching the list | None |
Adding, renaming, and removing
The first three methods are the safe ones. They change the list without losing data, or they fail loudly.
import pandas as pd
s = pd.Series(["a", "b", "a"], dtype="category")
s = s.cat.add_categories(["c"])
s.iloc[1] = "c"
s = s.cat.rename_categories({"a": "alpha"})
s = s.cat.remove_unused_categories()
print(s.tolist()) # ['alpha', 'c', 'alpha']
print(list(s.cat.categories)) # ['alpha', 'c']Each step does one thing:
add_categoriesmakes"c"a legal value. No row uses it yet.- The assignment replaces the
"b"row with"c". rename_categorieschanges the label"a"to"alpha"everywhere at once. It rewrites the category list, so the integer codes stay the same. This is much cheaper than rewriting every string in anobjectcolumn.remove_unused_categoriesdrops"b", which no row uses after step 2.
rename_categories also accepts a callable, for example s.cat.rename_categories(str.upper). A list must have exactly one entry per existing category, in the current order. A dict may name only the categories you want to change.
Why renaming cannot merge categories
Renaming two categories to the same label would make the category list contain duplicates, and pandas refuses with a ValueError. To merge categories, map the values and rebuild the dtype.
import pandas as pd
s = pd.Series(["red", "crimson", "blue", "red"], dtype="category")
merged = (
s.astype(object)
.replace({"crimson": "red"})
.astype("category")
)
print(list(merged.cat.categories)) # ['blue', 'red']
print(merged.tolist()) # ['red', 'red', 'blue', 'red']Going through object costs memory for a moment, but the result is correct and its categories are rebuilt from the data. If the original dtype was ordered, build a new CategoricalDtype yourself and pass it to astype, because the plain "category" call produces an unordered one.
Reordering and the ordered flag
The category list also defines the order that sorting and comparison use, if the dtype is ordered. A fresh categorical built from strings has its categories sorted alphabetically, which is rarely the logical order.
import pandas as pd
s = pd.Series(["lo", "hi", "mid", "lo"], dtype="category")
print(list(s.cat.categories)) # ['hi', 'lo', 'mid']
s = s.cat.reorder_categories(["lo", "mid", "hi"], ordered=True)
print(list(s.cat.categories)) # ['lo', 'mid', 'hi']
print(s.cat.codes.tolist()) # [0, 2, 1, 0]
print(s.max()) # hiThe codes changed from the alphabetical assignment because codes are positions in the list. Reordering rewrites the codes and leaves the labels attached to the right rows. reorder_categories requires the same set of labels as before. It cannot add or remove anything, which makes it the safest way to fix an order.
On a column that is already ordered, a reorder changes the result of <, max, and sort_values. Check any downstream filter such as s >= "mid" after you reorder.
set_categories and silent data loss
set_categories replaces the whole list in one step. It can add, remove, and reorder at once. That makes it convenient and also dangerous, because any existing value that is not in the new list becomes missing without a warning.
import pandas as pd
s = pd.Series(["lo", "hi", "mid", "lo"], dtype="category")
trimmed = s.cat.set_categories(["lo", "mid"])
print(trimmed.isna().tolist()) # [False, True, False, False]The "hi" row is now NaN. Compare isna().sum() before and after any set_categories call that removes labels. remove_categories has the same effect on the labels you name, so treat both as destructive.
Enforcing a fixed schema on incoming data
A common use of this behavior is validation. Define the allowed categories once, convert raw text with that dtype, and look at what failed to convert.
import pandas as pd
fixed = pd.CategoricalDtype(["lo", "mid", "hi"], ordered=True)
raw = pd.Series(["lo", "hi", "huge", "mid", None])
typed = raw.astype(fixed)
unexpected = raw[typed.isna() & raw.notna()]
print(unexpected.tolist()) # ['huge']
print(typed.isna().sum()) # 2astype with a CategoricalDtype turns unknown values into NaN instead of raising. The mask typed.isna() & raw.notna() separates values that were unknown from values that were already missing. Without this check, a misspelled label disappears into the missing values.
Reusing one CategoricalDtype object across files and columns also keeps their categories identical, which matters when you later combine the data.
Choosing the right method
The diagram summarizes which method fits which goal.
Edge cases to know
- Unused categories persist. Filtering rows with
df[df["size"] == "small"]keeps the full category list.value_countsthen shows zero counts for the missing labels, andgroupbymay too. Callremove_unused_categories()after filtering if you do not want them. - New data does not extend the list.
pd.concatof two columns with different category lists falls back toobject. Align the categories first. A later chapter covers combining in detail. - Order of categories is part of equality. Two unordered categoricals with the same labels in different orders hold the same data, but code comparisons such as
cat.codesgive different integers. - Whole-column assignment replaces the dtype. Writing
df["size"] = df["size"].str.upper()produces anobjectcolumn, because string methods on a categorical return plain strings. Userename_categories(str.upper)to stay categorical. - Missing values are not categories.
NaNnever appears in.cat.categories. Do not try to add it. Fill it withfillna("unknown")only after adding"unknown"as a category.
Summary
Categories are a closed list. To accept a new value, add it first. To rename or reorder, use the dedicated methods, since they keep the data intact. To replace the list wholesale, use set_categories and verify that nothing was lost. To merge labels, rebuild the dtype from mapped values.
Exercise
A column grade is categorical with categories ["A", "B", "C"]. You run df["grade"] = df["grade"].cat.set_categories(["A", "B"]). What happens to the rows that held "C", and how would you detect the problem?
Show answer
Those rows become NaN, because "C" is no longer in the category list, and pandas gives no warning. Compare df["grade"].isna().sum() before and after the call, or compare against the original column with orig.notna() & df["grade"].isna() to find the affected rows.
Exercise
You have a categorical Series s with categories ["small", "medium", "large"] (unordered) and you want sorting to follow small < medium < large. Which call does this, and why is rename_categories the wrong tool?
Show answer
Use s.cat.reorder_categories(["small", "medium", "large"], ordered=True). It keeps the same set of labels, fixes their order, and sets the ordered flag. rename_categories only changes label text. It cannot change the order or the ordered flag, so sorting would be unchanged.