Sub topic 14
Categorical keys and the observed parameter
This chapter assumes you know how to group by a column and aggregate with sum or mean. It also assumes you know what a pandas category dtype is, meaning a column that stores a fixed set of allowed values.
Why categorical keys behave differently
A categorical column knows its full list of categories, even the ones that never appear in the data. When you group by such a column, pandas has to decide whether to report only the categories present in the data or all declared categories. The observed parameter controls this choice.
observed=Truereturns only the categories that occur in the data.observed=Falsereturns every declared category, including empty ones.
The default depends on your version. In pandas 2.x the default is False, and relying on it raises a FutureWarning. In pandas 3.0 the default is True. Pass observed explicitly so your code gives the same result on both.
Seeing the difference
import pandas as pd
sizes = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
orders = pd.DataFrame({
"size": pd.Series(["small", "large", "small"], dtype=sizes),
"revenue": [10.0, 40.0, 20.0],
})
print(orders.groupby("size", observed=False)["revenue"].sum())
# size
# small 30.0
# medium 0.0
# large 40.0
# Name: revenue, dtype: float64
print(orders.groupby("size", observed=True)["revenue"].sum())
# size
# small 30.0
# large 40.0
# Name: revenue, dtype: float64No order has the size medium. With observed=False it still appears, with a sum of 0.0. Notice also that the groups follow the category order (small, medium, large), not alphabetical order.
Empty groups get the aggregation's value for no data. sum gives 0, and count and size give 0. mean, min, and max give NaN.
print(orders.groupby("size", observed=False)["revenue"].mean())
# size
# small 15.0
# medium NaN
# large 40.0
# Name: revenue, dtype: float64When to choose each setting
Use observed=False when the result should have a fixed shape. Examples are a report that always lists every size, or a table you will compare across months. Empty categories then show up as zeros instead of missing rows.
Use observed=True when you only care about what happened. It also avoids the next problem.
Multiple categorical keys multiply
With several categorical keys and observed=False, pandas builds every combination of categories, not only the combinations in the data. Two keys with 1,000 categories each can produce 1,000,000 result rows, most of them empty. This can use a lot of memory and time. If a groupby on categoricals is unexpectedly slow or large, check observed first.
orders["channel"] = pd.Categorical(
["web", "web", "store"], categories=["web", "store", "phone"]
)
full = orders.groupby(["size", "channel"], observed=False)["revenue"].sum()
seen = orders.groupby(["size", "channel"], observed=True)["revenue"].sum()
print(len(full), len(seen))
# 9 3Here 3 sizes times 3 channels gives 9 rows, but only 3 combinations occur in the data.
Common errors
- Surprise zero rows. A summary shows categories you never sold. The cause is
observed=False, and the fix isobserved=True. - Missing rows in a report. A category you expected is absent. The cause is
observed=Trueor the pandas 3.0 default, and the fix isobserved=False. - Warnings on upgrade. Code that omitted
observedwarns under pandas 2.x. Set the argument explicitly.
Exercise
A DataFrame has a categorical column tier with categories ["bronze", "silver", "gold"], but no row has "gold". What does df.groupby("tier", observed=False)["spend"].mean() return for gold, and what does observed=True return?
Show answer
With observed=False, gold appears with NaN, because the mean of no values is undefined. With observed=True, gold does not appear in the result at all.