skip to content

In pandas, why is a per-department z-score computed with groupby apply slow when there are many departments, and what do you replace it with?

level: seniorimportance: must knowfreq 65%

answer

  1. one Python call per group
  2. cost grows with group count
  3. result shape is inferred
  4. broadcast mean and std

basics

~20 s

groupby apply calls a Python function once per group and then concatenates the pieces and infers the result's shape, so its cost grows with the number of groups. (x - g.transform('mean')) / g.transform('std') computes the same z-score with grouped built-ins.

solid answer

~40 s

`df.groupby('dept')['amount'].apply(lambda x: (x - x.mean()) / x.std())` runs the lambda in Python for every department, builds a Series per group, then concatenates them and works out whether the result is a reduction, a transform or a filter. With thousands of small groups that overhead dominates. The rewrite `g = df.groupby('dept')['amount']` followed by `(df['amount'] - g.transform('mean')) / g.transform('std')` computes both statistics in pandas' grouped code and does the rest as whole-column arithmetic, giving the same values aligned to the original rows. Moving the same lambda into `transform` does not help, because it is still one Python call per group. A further trap: `apply` with the default `group_keys=True` returns a department-keyed MultiIndex, so assigning it straight back to a column raises `TypeError`.

code

python · 17 lines
python
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
n = 200_000
sales = pd.DataFrame({
    "dept": rng.integers(0, 20_000, n),
    "amount": rng.random(n) * 100,
})
g = sales.groupby("dept")["amount"]

slow = sales.groupby("dept", group_keys=False)["amount"].apply(
    lambda x: (x - x.mean()) / x.std()
).sort_index()
fast = (sales["amount"] - g.transform("mean")) / g.transform("std")

print(np.allclose(slow, fast, equal_nan=True))

go deeper

for a junior

Recall that groupby apply runs a Python function once per group and that built-in methods like transform('mean') are much faster.

for a middle

Explain the split, call and combine overhead of apply, why it scales with the number of groups, and how to rebuild a z-score from transform('mean') and transform('std').

for a senior

Show that you profile with a realistic group count, rewrite apply bodies into built-ins, verify equivalence with a tolerance and avoid the MultiIndex assignment trap.

for a principal

Set a review rule that grouped apply needs a reason, and weigh readability against cost for pipelines whose group counts grow with the business.

## Where apply's time goes `GroupBy.apply(func)` is pandas' most flexible grouped method: `func` may return a scalar, a Series or a DataFrame, and pandas works out how to combine them. That flexibility is paid for on every call: 1. **Split**: pandas builds a separate Series or DataFrame object for each group. 2. **Call**: the Python function runs once per group, and every pandas operation inside it carries its own fixed overhead. 3. **Combine**: the pieces are concatenated, and pandas must **infer** from what came back whether it was a reduction, a transformation or a filter, and how to index the result. Steps 1 and 2 cost roughly the same per group however small the group is, so the total grows with the **number of groups** far more than with the number of rows. With five departments, `apply` is merely somewhat slower than built-ins; with tens of thousands of small groups the gap can reach two orders of magnitude. The `apply` docstring itself warns that it "can be quite a bit slower than using more specific methods like `agg` or `transform`". The inference in step 3 has a second cost besides time. The user guide warns that `apply` "can sometimes guess wrong" about whether a result is a reduction, a transformation or a filter, so the same function can produce a differently shaped result when one group happens to return something unusual, such as an empty piece or a scalar. Specific methods fix the shape in advance: `agg` always returns one row per group, `transform` always returns the input's index, and `filter` always returns original rows. ## The built-in rewrite A **z-score within a department** is `(value - department mean) / department standard deviation`. Each piece already exists as a grouped built-in, and `transform` broadcasts it onto the rows: ```python g = sales.groupby("dept")["amount"] sales["z"] = (sales["amount"] - g.transform("mean")) / g.transform("std") ``` This runs two grouped reductions in compiled code and then does ordinary vectorized column arithmetic. It returns the same numbers as the lambda, including `NaN` for a one-row department, because pandas' `std` uses `ddof=1` in both forms. Note what does **not** help: `g.transform(lambda x: (x - x.mean()) / x.std())`. The function still runs once per group in Python; `transform` only guarantees the result's shape. ## Common apply bodies and their built-in versions | inside `apply` | built-in replacement | |---|---| | `x / x.sum()` | `s / g.transform('sum')` | | `x - x.mean()` | `s - g.transform('mean')` | | `x.fillna(x.mean())` | `s.fillna(g.transform('mean'))` | | `x.max() - x.min()` (per row) | `g.transform('max') - g.transform('min')` | | `x.cumsum()` | `g.cumsum()` | | `x.sort_values().head(2)` | sort once, then `groupby(...).head(2)` | | `len(x) >= 5` as a group filter | `df[g.transform('size') >= 5]` | Here `s` is the column and `g` the column's GroupBy object. ## A shape trap when assigning apply's result `groupby(...).apply` takes `group_keys=True` by default. When `func` returns a piece of each group, as the z-score lambda does, the result is indexed by **(department, original label)**. Assigning that to a column of the original frame fails: ```python sales["z"] = sales.groupby("dept")["amount"].apply(lambda x: x - x.mean()) # TypeError: incompatible index of inserted column with frame index ``` `group_keys=False` or `.droplevel(0)` fixes the index, but the transform rewrite avoids the issue and the cost together. ## When apply is still the right tool - The per-group logic has **no built-in equivalent**, such as fitting a small model or calling a domain function per group. - The number of groups is **small** and readability matters more than milliseconds. - The function returns a **different shape** per group, such as a summary table, that no other method can produce. Even then, select only the columns the function reads. For heavy numeric UDFs, `transform` and `agg` accept `engine='numba'`, which belongs with pandas performance tuning. ## Proving the rewrite is equivalent - Compare the old and new columns on real data with a tolerance, since the order of floating-point operations differs. - Check single-row and all-missing groups, where both forms should give `NaN`. - Time both on a production-sized sample with a realistic number of groups, not on a ten-row test frame. The general discipline of comparing two versions of a transform, such as tolerance and missing-value equality, is covered in the library-neutral lesson on correctness.

  • Is transform(lambda ...) faster than apply(lambda ...) for the same z-score?
    Not meaningfully. Both call the Python function once per group, so both scale with the number of groups. `transform` guarantees a same-indexed result, which avoids the MultiIndex assignment problem, but the speed comes only from replacing the lambda with string aliases such as `'mean'` and `'std'`.
  • Why does sales['z'] = ...apply(lambda x: x - x.mean()) raise TypeError?
    With the default `group_keys=True`, `apply` prefixes each returned piece with its group key, so the result has a MultiIndex of department and original label. That index cannot be aligned to the frame's single-level index, so the column insert raises `TypeError`. Use `group_keys=False`, or better, the built-in transform rewrite.

Sending one courier per parcel costs a trip each time, however small the parcel; loading every parcel onto one truck route costs about the same for ten parcels or ten thousand. apply is the courier per group, a grouped built-in is the truck.

  • apply is vectorized, so it costs about the same as a built-in
  • Moving the lambda from apply into transform makes it fast
  • apply's cost depends only on the number of rows, not the number of groups
  • apply's result can always be assigned back as a new column
  • The transform rewrite gives different numbers because std changes its ddof