Sub topic 14
Categorical keys and the observed parameter
This chapter explains what happens when you group by a column with the category dtype, and how the observed parameter controls which groups appear in the result. It assumes you can already build a DataFrame, select columns, and use groupby with sum, mean, and size. It also assumes you know what a pandas index is.
Why categorical keys behave differently
A categorical column stores a fixed list of allowed values, called categories, plus an integer code for each row. The list of categories belongs to the dtype. It does not depend on which values actually appear in the data.
For groupby, this means pandas knows about groups that have no rows. A plain string column has no such concept. Only values present in the data can form groups. A categorical column can have a category such as "XL" that no row uses. By default, pandas can still report that group.
Whether it does is controlled by observed:
observed=Truereturns only combinations of keys that appear in the data.observed=Falsereturns every category, or every combination of categories, including empty ones.
A first example
Build a small table in which one category is never used.
import pandas as pd
sizes = pd.CategoricalDtype(["S", "M", "L", "XL"], ordered=True)
orders = pd.DataFrame({
"size": pd.Series(["M", "S", "M", "L", "S"], dtype=sizes),
"qty": [2, 1, 3, 4, 5],
})
print(orders.groupby("size", observed=False)["qty"].sum())
# size
# S 6
# M 5
# L 4
# XL 0
# Name: qty, dtype: int64
print(orders.groupby("size", observed=True)["qty"].sum())
# size
# S 6
# M 5
# L 4
# Name: qty, dtype: int64Two things stand out. With observed=False, the empty XL group appears and its sum is 0. In both results the groups follow the category order (S, M, L, XL), not alphabetical order. The category order wins when the key is categorical.
Empty groups and aggregation results
An empty group gets the "identity" result of the aggregation, where one exists. For other aggregations it gets NaN.
| Aggregation | Result for an empty group |
|---|---|
| `sum` | `0` |
| `size`, `count` | `0` |
| `mean`, `min`, `max`, `median` | `NaN` |
| `first`, `last` | `NaN` |
For example, the mean forces a float result because NaN has to fit somewhere:
print(orders.groupby("size", observed=False)["qty"].mean())
# size
# S 3.0
# M 2.5
# L 4.0
# XL NaN
# Name: qty, dtype: float64This can be what you want. A report that must always list every size, even when nothing sold, needs the empty rows. Without them you would have to rebuild the missing rows by hand.
It can also mislead you. A 0 in a sum looks like a real measurement, but here it only means "no rows". If you need to tell apart "sold zero units" and "no orders at all", compare against size() or count() for the same group.
Choosing observed in the version you run
The default for observed has changed over time, so the same code can give different output in different versions.
- In pandas 2.x, the default is
observed=False. From pandas 2.1, leavingobservedunset when grouping by a categorical key raises aFutureWarningthat the default will change. - In pandas 3.0 and later, the default is
observed=True.
The safe habit is to pass observed explicitly whenever a key might be categorical. The code then behaves the same in every version, and the warning goes away.
Several categorical keys: the Cartesian product
The effect grows when you group by more than one categorical key. With observed=False, pandas builds every combination of categories across the keys. That is the Cartesian product, and many of its rows will be empty.
colors = pd.CategoricalDtype(["red", "blue"])
orders["color"] = pd.Series(
["red", "red", "blue", "red", "red"], dtype=colors
)
full = orders.groupby(["size", "color"], observed=False)["qty"].sum()
seen = orders.groupby(["size", "color"], observed=True)["qty"].sum()
print(len(full)) # 8
print(len(seen)) # 4The full result has 4 sizes times 2 colors, which is 8 rows. Only 4 combinations occur in the data.
The product grows multiplicatively. Three categorical keys with 100 categories each would produce one million rows, even if the data holds only a few hundred distinct combinations. This is a common cause of unexpectedly large memory use in groupby. If you only need the groups that exist, use observed=True.
Keeping keys as columns
as_index=False works as usual with categorical keys, and observed applies in the same way:
print(orders.groupby("size", observed=False, as_index=False)["qty"].sum())
# size qty
# 0 S 6
# 1 M 5
# 2 L 4
# 3 XL 0This gives you a flat table that you can merge or export without calling reset_index().
Deciding which setting to use
A practical rule: use observed=True for exploration and for most analysis. Use observed=False for fixed-layout reports, and check the product size first when there are several keys.
Removing unused categories instead
Sometimes you do not want empty groups at all, and the unused category is a leftover. This often happens after filtering rows, because the categories stay on the dtype. You can fix the data rather than the groupby call:
recent = orders[orders["qty"] > 1].copy()
recent["size"] = recent["size"].cat.remove_unused_categories()
print(recent["size"].cat.categories.tolist())
# ['M', 'L', 'S']Here S is still used by the row with quantity 5. XL is gone. Once the dtype carries only the categories that remain, observed=False and observed=True give the same groups.
Note that removing unused categories changes the dtype. If later code relies on the full list of categories, keep the original dtype and use observed instead.
Common errors and edge cases
- Missing
observedin pandas 2.x. You get aFutureWarning, and you may later get different output after an upgrade. Always set it. - Unexpected
NaNin a mean. An empty category producesNaNformean,min, andmax. If the column was an integer type, it becomes a float. - Row count explosion. Multiple categorical keys with
observed=Falsebuild the full product. Checklen(result)against what you expected. - Alphabetical order expected. Categorical groups follow the category order. If you need alphabetical order, change the dtype's categories or convert the key back with
astype(str). - Missing values in the key. A missing value is not a category. By default, rows with missing keys are dropped, and
dropna=Falsekeeps them, as described in the earlier chapter on missing keys. - Mixing categorical and non-categorical keys. Test the row count on a small sample before you rely on the result. The empty-group behavior depends on which keys are categorical.
A categorical key is also usually faster to group on than a string key. pandas can work with the integer codes instead of comparing strings. This helps on large tables with few distinct values, which is the usual case for categories.
Exercise
A DataFrame has a categorical column "tier" with categories ["bronze", "silver", "gold"], but no row has the value "gold". You run df.groupby("tier", observed=False)["spend"].mean(). What does the "gold" row contain, and how does the result change with observed=True?
Show answer
With observed=False, the result has a "gold" row and its mean is NaN, because the group is empty and the mean of no values is undefined. The spend column becomes float if it was not already. With observed=True, the "gold" row is not in the result at all, so only "bronze" and "silver" appear.
Exercise
You group by two categorical keys, one with 50 categories and one with 40 categories, using observed=False. About how many rows will the result have at most, and which setting avoids creating rows for combinations that never occur?
Show answer
The result has 50 x 40 = 2000 rows, because pandas builds every combination of categories. Setting observed=True keeps only the combinations that occur in the data.