Sub topic 9
Pitfalls with categorical columns
The category dtype can cut memory sharply, but it changes how a column behaves. Code that worked on strings can fail, return different results, or quietly use more memory than before. This chapter covers the failures you are most likely to meet and how to fix each one.
It assumes you can already convert a column with astype("category"). It also assumes you know that a categorical column stores a list of unique values (the categories) plus one small integer code per row. If that is new, read the previous chapter on categories and codes first.
The core rule: the categories are a closed set
A categorical column can only hold values that appear in its categories, or missing values. Most pitfalls come from forgetting this.
The table below lists the common situations and what happens in each.
| Operation | Behavior on a categorical column | Fix |
|---|---|---|
| Assign a value not in the categories | Raises an error | `cat.add_categories` first |
| `fillna` with a new value | Raises an error | Add the category, then fill |
| `groupby` on the column | May include categories with no rows | Pass `observed=True` |
| `<` or `>` on unordered categories | Raises `TypeError` | Use an ordered dtype |
| `concat` with different categories | Result falls back to `object` | Share one dtype, or use `union_categoricals` |
| Filter rows | Unused categories stay in the dtype | `remove_unused_categories` |
| Arithmetic on numeric categories | Raises an error | Convert back with `astype` |
Assigning values that are not categories
Suppose a column holds US and DE, and you try to write FR. The column has no slot for it.
import pandas as pd
s = pd.Series(["US", "DE", "US"], dtype="category")
try:
s.iloc[0] = "FR"
except (TypeError, ValueError) as exc:
print(type(exc).__name__, exc)
s = s.cat.add_categories(["FR"])
s.iloc[0] = "FR"
print(s.tolist())
print(s.cat.categories.tolist())The first assignment raises an error that tells you to set the categories first. After add_categories, the assignment works. The exception type differs between pandas versions, so the example catches both TypeError and ValueError.
fillna follows the same rule. s.fillna("unknown") fails if "unknown" is not already a category. Add it first, then fill.
This matters most in a pipeline where new data arrives later. A column converted from last month's file will reject a country that first appears this month. If new values are expected, either keep the column as object until the final step, or define the full category list up front (see the section on concatenation below).
groupby and the observed argument
A categorical column knows about every category, including ones with no rows. By default, groupby on a categorical column can produce a row for each of those empty categories.
import pandas as pd
country = pd.Categorical(["US", "DE", "US"], categories=["US", "DE", "FR"])
df = pd.DataFrame({"country": country, "score": [1.0, 2.0, 3.0]})
print(df.groupby("country", observed=False)["score"].mean())
print(df.groupby("country", observed=True)["score"].mean())With observed=False, the output has a row for FR, with NaN for the mean. With observed=True, only US and DE appear.
The difference gets expensive when you group by several categorical columns. With observed=False, pandas builds every combination of categories. Two columns with 1,000 categories each give a result with 1,000,000 rows, even if the data has only a few thousand real combinations. That can use more memory than the original column savings.
Set observed=True explicitly whenever you group by a categorical column. Recent pandas versions are changing the default toward True, but an explicit argument gives the same result on every version and avoids deprecation warnings.
Use observed=False only when you want the empty groups, for example a report that must list every product category even when one had no sales.
Unused categories
Filtering rows does not shrink the category list.
import pandas as pd
df = pd.DataFrame({
"country": pd.Series(["US", "DE", "FR", "US"], dtype="category"),
"n": [1, 2, 3, 4],
})
us_only = df[df["country"] == "US"]
print(us_only["country"].cat.categories.tolist())
print(us_only["country"].value_counts())
us_only = us_only.assign(
country=us_only["country"].cat.remove_unused_categories()
)
print(us_only["country"].cat.categories.tolist())After filtering, the column still lists US, DE and FR. value_counts reports 0 for the two that no longer occur. This surprises people who use value_counts to find the values present in a subset.
Calling remove_unused_categories() after a filter fixes both the counts and the stored category list. Do it before saving subsets, building charts, or calling groupby with observed=False.
Comparisons
Equality works on unordered categoricals. Ordering does not, because the column has no defined order.
import pandas as pd
unordered = pd.Series(["S", "L", "M"], dtype="category")
print((unordered == "L").tolist())
try:
print(unordered < "L")
except TypeError as exc:
print("TypeError:", exc)
order = pd.CategoricalDtype(["S", "M", "L"], ordered=True)
sizes = pd.Series(["S", "L", "M"], dtype=order)
print((sizes < "L").tolist())
print(sizes.max())The unordered column handles == but raises TypeError for <. A plain string column would compare alphabetically, so code that used < on strings will break after conversion. When the values have a real order, declare it with CategoricalDtype(..., ordered=True). Comparisons, min, max and sorting then follow your order (S < M < L), not alphabetical order.
Comparing a categorical to a scalar that is not in the categories behaves differently for == and <. == returns False for every row. < on an ordered column raises an error, because the scalar has no position in the order.
Two categorical columns can be compared with each other only if they have identical categories. Otherwise pandas raises TypeError. Make both columns use the same CategoricalDtype object first.
Concatenation and merges
When you concatenate categorical columns with different categories, pandas cannot keep the dtype. It falls back to object, and you lose the memory savings.
import pandas as pd
from pandas.api.types import union_categoricals
a = pd.Series(["US", "DE"], dtype="category")
b = pd.Series(["FR", "JP"], dtype="category")
print(pd.concat([a, b]).dtype)
merged = pd.Series(union_categoricals([a.array, b.array]))
print(merged.dtype)
print(merged.cat.categories.tolist())
shared = pd.CategoricalDtype(["US", "DE", "FR", "JP"])
a2 = pd.Series(["US", "DE"], dtype=shared)
b2 = pd.Series(["FR", "JP"], dtype=shared)
print(pd.concat([a2, b2]).dtype)The first concat gives object. union_categoricals builds a combined categorical from both. The third approach is better for repeated work: define one CategoricalDtype with every allowed value, then apply it to every chunk or file. All pieces then share the same categories, concat keeps the dtype, and the allowed values are written down in one place.
The same applies to merge and join. If the key columns are categoricals with different categories, the merge works on the values but the key column in the result may become object. Align the dtypes before merging.
Codes are not data
cat.codes returns the integer code behind each value. It is tempting to use these as a numeric feature, but the codes depend on the category order, which is arbitrary unless you set it. Two things to remember:
- Missing values have code
-1. Treat the code-1as "missing", not as a real number. - Codes from two columns with different category lists are not comparable, even for the same string.
Use the codes for diagnostics, as in the previous chapter. For modelling, use a proper encoding such as one-hot, or an ordered dtype if the order is real.
Numeric categories
You can convert an integer column to category, for example a column of ZIP codes or small status numbers. The result no longer supports arithmetic.
import pandas as pd
levels = pd.Series([3, 1, 2, 3], dtype="category")
try:
print(levels + 1)
except TypeError as exc:
print("TypeError:", exc)
print((levels.astype("int64") + 1).tolist())The addition raises TypeError. Convert back with astype("int64") when you need numbers. Also note that levels.astype("int64") creates a full-size copy, so a loop that converts back and forth can cost more than it saves.
For integer columns, downcasting (the earlier chapters) is almost always the better tool than category. It keeps arithmetic working. Use category on numbers only for identifiers that you never calculate with.
Deciding in practice
The diagram shows the checks to run before converting a column, and what to do on each answer.
A defensive pattern
Combine the fixes above into a small routine. It applies a shared dtype, checks for values that fall outside it, and trims unused categories after filtering.
import pandas as pd
ALLOWED = pd.CategoricalDtype(["US", "DE", "FR", "JP", "BR"])
def to_country(series):
out = series.astype(ALLOWED)
unexpected = series[out.isna() & series.notna()].unique()
if len(unexpected) > 0:
raise ValueError(f"Unexpected countries: {list(unexpected)}")
return out
raw = pd.Series(["US", "DE", "US", "JP"])
country = to_country(raw)
print(country.dtype)
subset = country[country == "US"].cat.remove_unused_categories()
print(subset.cat.categories.tolist())
try:
to_country(pd.Series(["US", "ES"]))
except ValueError as exc:
print(exc)Converting with astype(ALLOWED) turns any value outside the list into NaN without an error. The check compares the result to the original and raises if a non-missing value was lost. Without it, a typo or a new country would silently become missing data.
Summary of habits
- Treat the category list as part of the schema. Define it once and reuse it.
- Add categories before assigning or filling with a new value.
- Pass
observed=Truetogroupby, unless you need empty groups. - Call
remove_unused_categories()after filtering a subset. - Use ordered dtypes for values with a real order, and do not rely on
<for unordered ones. - Keep calculations on real numeric dtypes, and use
categoryonly for labels. - Check memory again after a
concatormerge. A silent fall back toobjectundoes the savings.
Exercise
A DataFrame has a categorical column product with 2,000 categories and another categorical column store with 500 categories. The data has 40,000 rows and about 30,000 real product-store pairs. A colleague runs df.groupby(["product", "store"], observed=False)["sales"].sum() and the process runs out of memory. Explain why, and give the fix. Then say what you would do to the product column after you filter the frame to a single store.
Show answer
With observed=False, pandas builds every combination of categories, so the result can have 2,000 × 500 = 1,000,000 rows, far more than the 30,000 real pairs. Use observed=True so only combinations present in the data appear. After filtering to one store, the product column still lists all 2,000 categories, so call df["product"] = df["product"].cat.remove_unused_categories() to drop the ones with no rows. This keeps value_counts and later groupby calls from reporting empty categories.