Sub topic 15
Pitfalls and performance
This chapter assumes you know agg, transform, filter, and apply, and that you can read a groupby result's index. It covers the mistakes that produce wrong numbers without raising an error, and the habits that keep groupby fast.
Pitfalls that change your results
| Pitfall | What happens | Fix |
|---|---|---|
| Missing group keys | Rows with a missing key are dropped silently | Use `dropna=False` if you need them |
| `count` used as a row count | Missing values are skipped | Use `size()` for rows |
| Non-numeric columns in `mean` or `sum` | Raises `TypeError` in recent pandas | Select the columns you need first |
| Categorical keys | Unused categories appear as empty groups | Set `observed` explicitly |
| Assuming sorted output | Groups are sorted by key by default | Pass `sort=False` if order is irrelevant |
Select columns before aggregating. df.groupby("region")[["units", "revenue"]].mean() is explicit and avoids errors from text columns.
Categorical keys and observed
A categorical column knows all of its categories, including ones that never occur in the data. With observed=False, groupby returns a row for every category.
import pandas as pd
df = pd.DataFrame({
"size": pd.Categorical(["S", "S", "L"], categories=["S", "M", "L"]),
"v": [1, 2, 3],
})
print(df.groupby("size", observed=False)["v"].sum())
# size
# S 3
# M 0
# L 3
# Name: v, dtype: int64
print(df.groupby("size", observed=True)["v"].sum())
# size
# S 3
# L 3
# Name: v, dtype: int64Older pandas versions defaulted to observed=False, and newer ones default to observed=True. Some versions warn when you rely on the default. Always pass the argument so your code behaves the same everywhere.
With several categorical keys, observed=False returns every combination of categories. That can produce a very large result with many empty rows.
Performance
The built-in aggregations (sum, mean, min, max, count, size, nunique, first) run in compiled code. A Python function passed to apply runs once per group. When there are many groups, that call overhead dominates.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
big = pd.DataFrame({
"k": rng.integers(0, 10_000, 1_000_000),
"v": rng.random(1_000_000),
})
start = time.perf_counter()
slow = big.groupby("k")["v"].apply(lambda s: s.sum())
t_apply = time.perf_counter() - start
start = time.perf_counter()
fast = big.groupby("k")["v"].sum()
t_builtin = time.perf_counter() - start
print(np.allclose(slow, fast)) # True
print(f"apply: {t_apply:.3f}s, built-in: {t_builtin:.3f}s")Both versions give the same answer. Timings vary by machine, but the built-in call is usually many times faster.
Guidelines:
- Prefer a built-in name, such as
"sum", over a lambda wherever one exists. - Use
transform("sum"), nottransform(lambda s: s.sum()). The string form takes the fast path. - Compute vectorized columns first, then aggregate. For a weighted total, create
df["weighted"] = df["units"] * df["revenue"]and sum it by group, instead of usingapplyon each group. - Use
sort=Falsewhen output order does not matter. Skipping the sort saves work on many groups. - Keep
applyfor logic that truly needs the whole group, such as returning the top two rows per group.
Exercise
A DataFrame has a categorical column "tier" with categories "gold", "silver", and "bronze". No row has "bronze". You run df.groupby("tier", observed=False)["spend"].mean(). What does the "bronze" row contain, and what argument would remove it?
Show answer
The "bronze" row appears with NaN, because the mean of an empty group is undefined. Passing observed=True removes it, because only categories that occur in the data are returned.
Exercise
You need each row's spend divided by its group's maximum spend, on a table with 500,000 groups. Which is better: transform("max") or transform(lambda s: s.max())? Why?
Show answer
transform("max"). The string uses a compiled implementation. The lambda runs Python code once per group, which is slow with 500,000 groups.