Sub topic 6
Managing categories safely
This chapter assumes you can create a categorical column and read its .cat.categories and .cat.codes, as covered earlier. The .cat accessor also lets you change the category set. Categories are a fixed list, so changes fall into two kinds. Some only edit the list. Others change what the rows mean.
The category set is a contract
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] = "c"
except (TypeError, ValueError) as err:
print("Rejected:", err)The error is a TypeError in pandas 2.x. Older versions raised ValueError. The fix is to extend the categories first, then assign.
Adding, renaming, and removing
Each .cat method returns a new Series. Assign the result back, or the change is lost.
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']Here is what each step does:
add_categoriesappends new categories at the end. No row changes.rename_categorieschanges labels only. The integer codes stay the same. It accepts a dict or a list with one new name per existing category.remove_unused_categoriesdrops categories that no row uses. Because none are in use, no data is lost.
After the b row was overwritten, b was an unused category. That is why remove_unused_categories removed it.
Operations that can lose data
remove_categories and set_categories can delete categories that rows still use. Those rows become missing values (NaN), with no warning.
import pandas as pd
s = pd.Series(["a", "b", "c"], dtype="category")
t = s.cat.set_categories(["c", "b", "z"])
print(t.tolist()) # [nan, 'b', 'c']
print(list(t.cat.categories)) # ['c', 'b', 'z']set_categories replaces the whole category list in one call. It can add (z), drop (a), and reorder in a single step. The row that held a became NaN, because a is no longer a valid category.
Check for accidental loss by comparing missing-value counts before and after:
print(s.isna().sum(), t.isna().sum()) # 0 1Reordering
reorder_categories changes the order of categories without changing which ones exist. It requires the new list to contain exactly the same categories, so it cannot silently drop values.
import pandas as pd
sizes = pd.Series(["small", "large", "medium"], dtype="category")
sizes = sizes.cat.reorder_categories(["small", "medium", "large"], ordered=True)
print(sizes.max()) # largeOrder only matters for comparisons and sorting when ordered=True. For an unordered categorical, sort_values still follows the category order, and max raises an error.
Choosing the right method
| Method | Changes rows? | Safe from data loss? |
|---|---|---|
| `add_categories` | No | Yes |
| `rename_categories` | Labels only | Yes |
| `reorder_categories` | No | Yes, same set required |
| `remove_unused_categories` | No | Yes |
| `remove_categories` | Rows may become `NaN` | No |
| `set_categories` | Rows may become `NaN` | No |
Common errors
- Forgetting to assign the result of a
.catmethod back to the Series. - Renaming with a list of the wrong length. The list needs one name for every existing category.
- Using
set_categoriesto reorder, then findingNaNvalues because a category was left out of the new list. Preferreorder_categoriesfor pure reordering. - Merging two labels by renaming both to the same name. Recent pandas versions reject duplicate category names, so map rows to the target label before removing the old one.
Exercise
A Series s has categories ["x", "y", "z"], and no row holds y. You run s.cat.set_categories(["x", "z", "w"]). How many rows become NaN, and what would you call instead to drop only y?
Show answer
None become NaN, because no row held y, and x and z stay in the new list. The safer call is s.cat.remove_unused_categories(), or s.cat.remove_categories(["y"]) if you want to name y explicitly. If a row had held y, remove_categories would turn it into NaN, but remove_unused_categories would leave it alone.