Sub topic 13
Pitfalls and best practices
This chapter pulls together the failure modes from earlier chapters and turns them into working rules. It assumes you know how categories and codes work, how the .cat accessor behaves, and how groupby and value_counts work. Most categorical bugs fall into three groups: values outside the category set, categories that differ between objects, and code that treats codes or unused categories as real data.
When a categorical is the wrong choice
A categorical pays off when a column has few distinct values that repeat many times. Each row stores a small integer, and the strings are stored once in the categories. If almost every value is unique, the categories array is as large as the original data and you also pay for the code array.
The decision also depends on what you do with the column afterwards. Categoricals help with grouping, sorting by a defined order, and compact storage. They get in the way when you need arithmetic or free-form string edits.
A small helper makes the first check repeatable. It converts only columns whose ratio of distinct values to rows is low.
import pandas as pd
from pandas.api.types import is_object_dtype, is_string_dtype
def categorize_low_cardinality(df, max_ratio=0.5):
out = df.copy()
for col in out.columns:
s = out[col]
if is_object_dtype(s) or is_string_dtype(s):
ratio = s.nunique() / max(len(s), 1)
if ratio <= max_ratio:
out[col] = s.astype("category")
return out
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Rome", "Oslo", "Rome"],
"order_id": ["a1", "a2", "a3", "a4", "a5", "a6"],
})
print(categorize_low_cardinality(df).dtypes)city has a ratio of 2/6, so it becomes category. order_id has a ratio of 1.0, so it keeps its original dtype. The 0.5 threshold is a starting point. Measure with memory_usage(deep=True) on your own data before you rely on it.
Values outside the category set
A categorical accepts only values that are in its categories (or missing). Assigning anything else fails. Methods such as fillna and where fail the same way when the replacement is not a category.
import pandas as pd
s = pd.Series(["a", "b", "a"], dtype="category")
try:
s.iloc[0] = "z"
except (TypeError, ValueError) as err:
print("rejected:", type(err).__name__)
s = s.cat.add_categories(["z"])
s.iloc[0] = "z"
print(s.tolist()) # ['z', 'b', 'a']The exception type has changed between pandas versions, so catch both TypeError and ValueError if you handle it. The fix is to add the category first. For data that arrives continuously, define the full category list once, for example from a reference table, and apply it with CategoricalDtype. Then new data is validated against a known set.
Values that do not match a given dtype become missing instead of raising when you build a categorical with dtype=. A typo such as "Smal" silently turns into NaN. After conversion, compare missing counts before and after:
import pandas as pd
raw = pd.Series(["small", "large", "Smal", "medium"])
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
typed = raw.astype(size_type)
print(raw.isna().sum(), typed.isna().sum()) # 0 1
print(raw[typed.isna()].tolist()) # ['Smal']This check catches data-cleaning problems that a conversion would otherwise hide.
Categories that differ between objects
Two categoricals with different category sets are different dtypes. Operations that mix them often fall back to object, which erases the memory and speed gains without any warning.
import pandas as pd
a = pd.Series(["x", "y"], dtype="category")
b = pd.Series(["y", "z"], dtype="category")
print(pd.concat([a, b], ignore_index=True).dtype) # object
shared = pd.CategoricalDtype(["x", "y", "z"])
fixed = pd.concat(
[a.astype(shared), b.astype(shared)], ignore_index=True
)
print(fixed.dtype) # categoryWhen you cannot know the full set ahead of time, pandas.api.types.union_categoricals builds the union of categories for you. The same issue appears in merge and join. If the key columns have different category sets, the result may drop to object. Give both sides the same CategoricalDtype before merging.
Comparisons have a similar rule. Comparing two unordered categoricals with different categories raises TypeError. Comparing ordered categoricals requires identical categories in identical order.
Groupby and unobserved categories
Grouping by a categorical key can produce one result row per category, including categories that do not occur in the data. That is controlled by observed. Through pandas 2.x the default was False, and the default is changing to True in pandas 3.0. Code that relies on the default can change its output after an upgrade.
import pandas as pd
level = pd.CategoricalDtype(["low", "mid", "high"])
df = pd.DataFrame({
"level": pd.Series(["low", "low", "high"], dtype=level),
"value": [1, 2, 3],
})
full = df.groupby("level", observed=False)["value"].sum()
seen = df.groupby("level", observed=True)["value"].sum()
print(full.index.tolist()) # ['low', 'mid', 'high']
print(seen.index.tolist()) # ['low', 'high']Choose by purpose:
- Use
observed=Falsefor reports where every category must appear, such as a table of all rating levels with zeros for empty ones. - Use
observed=Truefor analysis, and especially when grouping by several categorical columns. Withobserved=False, the result contains every combination of categories, which can create a huge, mostly empty table.
Always pass observed explicitly so the code means the same thing on every pandas version.
Unused categories after filtering
Filtering rows does not remove categories. The dtype keeps its full category list, and later steps see categories with zero rows.
import pandas as pd
s = pd.Series(["a", "b", "c", "a"], dtype="category")
subset = s[s == "a"]
print(subset.value_counts().to_dict())
# {'a': 2, 'b': 0, 'c': 0}
subset = subset.cat.remove_unused_categories()
print(subset.value_counts().to_dict())
# {'a': 2}Plots, value_counts, and get_dummies all reflect the zero-count categories. Decide deliberately. Keep them if the full category list matters, for example so that train and test sets encode the same columns. Remove them if they are noise.
Codes are not data
.cat.codes is an implementation detail: the position of each value in the category list, with -1 for missing. It changes when you reorder or add categories, and for an unordered categorical the numbers carry no meaning.
Two mistakes follow from this:
- Using codes as a numeric feature. A model reads code 2 as "twice code 1", which is false for unordered data such as colors.
- Expecting numeric categories to behave like numbers. A categorical of
"10"and"20"stores positions 0 and 1, not 10 and 20.
import pandas as pd
s = pd.Series(["10", "20", "10"], dtype="category")
print(s.cat.codes.tolist()) # [0, 1, 0]
print(s.astype(int).tolist()) # [10, 20, 10]If you need the numeric values, convert with astype. If you need numeric arithmetic on a column, such as sum or mean, convert it to a numeric dtype first. Categoricals do not support those reductions, except for min and max on ordered ones.
Reading and writing
Plain-text formats such as CSV store strings only. A categorical written to CSV comes back as object, and any category order is lost. Parquet and Feather preserve the categorical dtype, including order. For CSV, restore the dtype explicitly on read with the dtype= argument of read_csv, passing a CategoricalDtype per column, so you get the right order and category set instead of whatever happens to be in the file.
Best practices checklist
- Measure before converting. Check
memory_usage(deep=True)and the ratio of distinct values to rows. - Define categories once, in one place, and reuse the same
CategoricalDtypefor every dataset that must be compared, concatenated, or merged. - Use
ordered=Trueonly when the order is real. Do not use it for labels such as colors or cities. - Compare missing-value counts before and after conversion to catch typos.
- Pass
observedexplicitly in everygroupbyon a categorical key. - Call
remove_unused_categories()after filtering unless the full list is needed. - Never feed
.cat.codesof an unordered column into a model as a number. Use one-hot encoding, or codes only for ordered data where the order is meaningful. - Store intermediate data in Parquet or Feather to keep the dtype.
- Add a dtype assertion at the boundaries of a pipeline, for example
assert df["size"].dtype == size_type, so a silent fall back toobjectfails loudly.
Exercises
Exercise
You run pd.concat([a, b]) on two categorical Series and the result has dtype object. What is the likely cause, and how do you keep category?
Show answer
The two Series have different category sets, so they are different dtypes and pandas falls back to object. Convert both to the same CategoricalDtype (a shared list of categories) before concatenating, or combine them with pandas.api.types.union_categoricals.
Exercise
A DataFrame has a categorical column grade with categories A, B, C, D. After filtering to rows where grade is "A" or "B", groupby("grade", observed=False).size() still returns rows for C and D. Give two ways to get only A and B.
Show answer
Pass observed=True to groupby, or call df["grade"] = df["grade"].cat.remove_unused_categories() after filtering. Both leave only the categories that occur in the data.
Exercise
Why is s.cat.codes a poor numeric feature for an unordered column of colors, and what should you use instead?
Show answer
The codes are positions in the category list, so a model would treat them as ordered quantities (blue = 2 is "more" than green = 1), which is meaningless for colors. They also change if categories are reordered. Use one-hot encoding instead.