Sub topic 9
Pitfalls with categorical columns
This chapter assumes you can convert a column with astype("category") and know that a categorical column stores a list of categories plus an integer code per row. It covers four problems that appear after the conversion: new values, groupby output, comparisons, and combining frames.
Pitfall 1: values outside the categories
A categorical column accepts only values that are already in its category list. Assigning anything else fails.
import pandas as pd
s = pd.Series(["US", "DE", "US"], dtype="category")
try:
s[0] = "FR"
except (TypeError, ValueError) as e:
print("assignment failed:", type(e).__name__)
s = s.cat.add_categories("FR")
s[0] = "FR"
print(s.tolist())The exact exception class depends on your pandas version, so catch both TypeError and ValueError. Register new values first with cat.add_categories. Values you read from a file are different. They become categories automatically when you convert the column. The failure only happens when you write into an existing categorical column.
Pitfall 2: groupby shows unused categories
A categorical keeps every category, even one that no row uses. By default, groupby can report a group for each category. This happens after you filter rows, or when you build a column with a fixed category list.
import pandas as pd
df = pd.DataFrame({
"country": pd.Categorical(["US", "DE", "US"], categories=["US", "DE", "FR"]),
"score": [1.0, 2.0, 3.0],
})
print(df.groupby("country", observed=False)["score"].sum())
print(df.groupby("country", observed=True)["score"].sum())The first call returns a row for FR with a sum of 0. The second returns only US and DE. Recent pandas versions warn when you leave observed unset, and pandas 3 will default to observed=True. Pass it explicitly so your results do not change when you upgrade.
Unused categories can also grow the output of value_counts and pivot tables. After filtering, call cat.remove_unused_categories() to drop them.
Pitfall 3: comparisons and ordering
An unordered categorical supports == and !=. It does not support < or >, because the categories have no defined order. Comparing two categorical columns also fails unless both have identical categories.
import pandas as pd
a = pd.Series(["US", "DE"], dtype="category")
print((a == "US").tolist())
try:
a < "US"
except TypeError:
print("ordering needs ordered=True")
sizes = pd.Series(
pd.Categorical(["S", "L", "M"], categories=["S", "M", "L"], ordered=True)
)
print((sizes < "L").tolist())If the order is meaningful, as with sizes or ratings, declare it with ordered=True and list the categories in that order. Sorting then follows the category order, not alphabetical order.
Pitfall 4: combining frames silently loses the dtype
When you concatenate two categorical columns with different categories, pandas falls back to object. You lose the memory savings, and nothing warns you.
import pandas as pd
from pandas.api.types import union_categoricals
a = pd.Series(["US", "DE"], dtype="category")
b = pd.Series(["FR", "US"], dtype="category")
print(pd.concat([a, b]).dtype)
combined = union_categoricals([a, b])
print(pd.Series(combined).dtype)
print(list(combined.categories))The first print shows object. union_categoricals builds one shared category list, and the second print shows category. If you load data in chunks, check the dtypes after every concatenation. A common alternative is to define the full category list up front and apply it to every chunk.
Quick reference
| Symptom | Cause | Fix |
|---|---|---|
| Error when assigning a value | Value is not in the categories | `cat.add_categories` |
| Empty groups in results | `observed=False` | `observed=True` |
| `TypeError` on `<` or `>` | Categories are unordered | `ordered=True` |
| Column becomes `object` after `concat` | Category lists differ | `union_categoricals` |
| Old categories remain after filtering | Categories are not pruned | `cat.remove_unused_categories()` |
Exercise
You filter a categorical country column down to the rows where country is "US". Then you run df.groupby("country")["score"].mean() on pandas 2.x and see rows for countries that no longer appear in the data. Why does this happen, and give two ways to remove those rows.
Show answer
The column still holds its full category list, and groupby with observed=False reports a group for every category. Either pass observed=True to groupby, or call df["country"].cat.removeunusedcategories() after filtering so the unused categories are removed from the column itself.