Sub topic 12
Using apply with groupby
This chapter assumes you know Series.apply and DataFrame.apply, and that you can write a groupby call with a single key. Pandas 2.2 or later is assumed. Where older versions behave differently, the text says so.
What groupby apply does
groupby splits a table into groups. apply calls your function once per group and combines the results. This is the split-apply-combine pattern.
The earlier methods in this tutorial passed your function an element, a column, or a row. On grouped data, the function receives the whole group:
- On a
SeriesGroupBy(for exampledf.groupby("team")["score"]), each call receives a Series holding one group's values. - On a
DataFrameGroupBy(for exampledf.groupby("team")), each call receives a DataFrame holding one group's rows.
The function runs once per group, not once per row. That is cheaper than row-wise apply when groups are large. It is expensive when there are thousands of tiny groups.
A scalar per group
The simplest case is a function that reduces each group to one number.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
print(df.groupby("team")["score"].apply(lambda s: s.max() - s.min()))The output is a Series indexed by the group keys:
team
x 6
y 2
Name: score, dtype: int64Pandas calls the lambda with Series([3, 9]) for team x and Series([4, 6]) for team y. It collects the two scalars and labels them with the keys.
Working with the whole group
On a DataFrameGroupBy, the function sees every column, so it can use several columns at once. This is the main reason to reach for grouped apply instead of agg.
import pandas as pd
df = pd.DataFrame(
{
"team": ["x", "x", "y", "y"],
"player": ["ann", "bob", "cy", "di"],
"score": [3, 9, 4, 6],
}
)
best = df.groupby("team")[["player", "score"]].apply(
lambda g: g.nlargest(1, "score")
)
print(best)Each call receives a small DataFrame with player and score. It returns a one-row DataFrame with that team's top scorer. Pandas stacks those frames. The result has a two-level index: the team key, then the original row label.
The grouping columns in the function input
Older pandas versions included the grouping column (team) in each group DataFrame. Since pandas 2.2, calling df.groupby("team").apply(func) emits a DeprecationWarning for this behavior. In pandas 3.0 the grouping columns will be excluded.
There are two ways to avoid depending on this:
- Select the columns you need before
apply, as the example above does with[["player", "score"]]. This is the clearest option, because the function's input is explicit. - Pass
include_groups=Falsetoapplyto exclude the grouping columns now.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
result = df.groupby("team").apply(
lambda g: g["score"].sum(), include_groups=False
)
print(result)If your function reads the key column from inside the group, for example g["team"].iloc[0], it breaks when the column is excluded. Use g.name instead. g.name holds the group key for each call.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
def label_total(g):
return f"{g.name}: {g['score'].sum()}"
print(df.groupby("team")[["score"]].apply(label_total))What the function returns decides the shape
Pandas inspects the return values and picks a way to combine them. The rules match the ones for DataFrame.apply, with group keys playing the role of labels.
| Function returns | Result |
|---|---|
| A scalar | A Series indexed by the group keys |
| A Series (same labels for every group) | A DataFrame, one row per key, with the Series labels as columns |
| A DataFrame or Series whose index differs from the input group | The pieces are concatenated, with the group key added as an outer index level |
| A DataFrame or Series with the same index as the input group | A transform-like result, aligned to the original rows (see `group_keys` below) |
Returning a Series per group is a convenient way to compute several statistics that depend on each other:
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
stats = df.groupby("team")[["score"]].apply(
lambda g: pd.Series(
{"range": g["score"].max() - g["score"].min(), "mean": g["score"].mean()}
)
)
print(stats)The result is a DataFrame indexed by team with columns range and mean.
Returning data shaped like the input
If the function returns an object with the same index as its input group, pandas treats it as a transform. The group_keys argument of groupby controls whether the keys are added as an extra index level. Since pandas 2.0 the default is group_keys=True, so keys are added.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
centered = df.groupby("team", group_keys=False)["score"].apply(
lambda s: s - s.mean()
)
print(centered)With group_keys=False, the result keeps the original row labels 0 to 3, so you can assign it back as a column. With the default True, the index would have the team key as an extra level and assignment would not align.
For this particular task, transform is the better tool, as the next section explains.
Use a built-in aggregation when one exists
apply is the most general grouped method, and it is also the slowest and least explicit. Pandas offers three related methods:
| Method | Function must return | Output shape |
|---|---|---|
| `agg` | One value per group (per column) | One row per group |
| `transform` | A result with the same length as the group, or a scalar that is broadcast | Same index as the original |
| `apply` | Anything: scalar, Series, or DataFrame | Depends on what is returned (see the table above) |
Many tasks that people write with apply already have a faster form:
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
# Per-group range, using built-in aggregations
spread = df.groupby("team")["score"].agg(["min", "max"])
spread["range"] = spread["max"] - spread["min"]
print(spread)
# Each score as a share of its team total, aligned to the original rows
df["share"] = df["score"] / df.groupby("team")["score"].transform("sum")
print(df)String names such as "sum", "mean", "min" and "max" run in compiled code. A lambda passed to apply or agg runs as Python once per group. Use apply when the logic needs the whole group at once, such as selecting rows, comparing columns, or fitting a small model.
Pitfalls specific to grouped apply
Many small groups are slow
The Python function runs once per group. With a million rows and 500,000 groups, you make 500,000 Python calls plus the cost of building a Series or DataFrame for each. Check whether an agg, transform, nlargest-style method, or cumsum on the grouped object does the job.
Mutating the group
The group passed to your function may be a view of the original data or a copy, depending on pandas version and code path. Do not modify it in place. Build and return a new object.
Missing keys are dropped
Rows whose group key is NaN or None are excluded by default, so they never reach your function. Pass dropna=False to groupby if you need them.
import pandas as pd
df = pd.DataFrame({"team": ["x", None, "x"], "score": [1, 2, 3]})
print(df.groupby("team")["score"].sum())
print(df.groupby("team", dropna=False)["score"].sum())The first call reports only team x. The second adds a row for the missing key.
Inconsistent return types
If the function returns a scalar for some groups and a Series for others, the combined result is unpredictable or raises an error. Return the same kind of object from every branch, including special cases such as empty groups.
Categorical keys
When the key column has a categorical dtype, groups for categories that never occur may still be produced, and your function then receives an empty group. The observed parameter of groupby controls this. Setting observed=True returns only categories that appear in the data. Make sure the function can handle empty input, or avoid the case with observed=True.
Summary of decisions
- If a built-in aggregation (
sum,mean,aggwith named functions) gives the answer, use it. - If you need a per-row result computed from group statistics, use
transform. - If the logic needs several columns or the whole group, or must return rows, use
apply, and select the columns it needs beforehand. - Return the same type of object from every group, and do not mutate the input.
Exercise
Given df = pd.DataFrame({"team": ["x", "x", "y", "y"], "player": ["ann", "bob", "cy", "di"], "score": [3, 9, 4, 6]}), write a grouped apply that returns, for each team, the name of the player with the highest score. What shape does the result have?
Show answer
Use df.groupby("team")[["player", "score"]].apply(lambda g: g.loc[g["score"].idxmax(), "player"]). The function returns a scalar for each group, so the result is a Series indexed by team: x maps to "bob" and y maps to "di". Selecting the two columns first avoids the grouping-column deprecation warning.
Exercise
You want a new column "centered" on df holding each score minus its team mean, aligned to the original rows. Which grouped method is the best fit, and why would groupby(...).apply(lambda s: s - s.mean()) with the default settings be awkward?
Show answer
Use df["centered"] = df["score"] - df.groupby("team")["score"].transform("mean"). transform returns a result with the original index and runs the mean in compiled code. With apply and the default groupkeys=True, the returned index gains the team key as an extra level, so assigning it to a column does not align with the original rows unless you set groupkeys=False.