Sub topic 12
Custom logic with apply
apply is the general-purpose method on a GroupBy object. It runs a function of your own on each group and then works out how to combine the results. This chapter assumes you can already use groupby with built-in aggregations, agg, transform, and filter, and that you know the difference between a Series and a DataFrame. Examples use pandas 2.2 or later.
What apply does
apply splits the data into groups and passes each group to your function as a DataFrame. It collects whatever the function returns and chooses a combine strategy based on the return values. This flexibility is why it is called the "escape hatch" of groupby. It is also why it is easy to misuse.
The shape of the result depends on what your function returns:
| Function returns | Combined result |
|---|---|
| A scalar | A Series indexed by the group keys, like `agg` |
| A Series | A DataFrame with one row per group and the Series index as columns |
| A DataFrame with a different index than the input | The pieces are concatenated, usually under a MultiIndex of group key and original index |
| A DataFrame or Series with the same index as the input | Behaves like `transform`, aligned to the original rows |
Setup
The examples in this chapter reuse this DataFrame.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})Returning a Series per group
A function that returns a Series produces one output row per group. The Series labels become the column names. This is the usual way to compute several statistics that depend on each other, which named aggregation cannot express because each output there uses only one column.
def summarize(g):
total_revenue = g["revenue"].sum()
return pd.Series({
"revenue": total_revenue,
"price_per_unit": total_revenue / g["units"].sum(),
})
result = df.groupby("region").apply(summarize, include_groups=False)
print(result)
# revenue price_per_unit
# region
# North 175.0 11.666667
# South 220.0 12.222222Here price_per_unit is total revenue divided by total units. That is not the mean of per-row prices, so no single built-in aggregation produces it.
Returning a DataFrame per group
When the function returns a DataFrame, apply stacks the pieces. A common use is "top N rows per group".
def top_revenue(g):
return g.nlargest(1, "revenue")
top = df.groupby("region").apply(top_revenue, include_groups=False)
print(top)
# product units revenue
# region
# North 0 A 10 100.0
# South 4 B 8 120.0The result has a two-level index. The first level is the group key and the second is the original row label. This comes from the group_keys parameter, which defaults to True. If you want the original index back, pass group_keys=False.
top_two = df.groupby("region", group_keys=False).apply(
lambda g: g.nlargest(2, "revenue"), include_groups=False
)
print(top_two)
# product units revenue
# 0 A 10 100.0
# 1 B 5 75.0
# 4 B 8 120.0
# 2 A 7 70.0Rows come out in group order, then in the order the function returned them. That is why the labels read 0, 1, 4, 2.
The include_groups parameter
By default older code passes each group with the grouping columns still inside it. In pandas 2.2, doing this emits a DeprecationWarning. Passing include_groups=False removes the grouping columns (here region) from each group before your function sees it. This is the behavior going forward, so use it in new code.
If you need the key inside the function, use g.name:
def label_total(g):
return f"{g.name}: {g['revenue'].sum():.0f}"
print(df.groupby("region").apply(label_total, include_groups=False))
# region
# North North: 175
# South South: 220
# dtype: objectapply on a single column
If you select a column before calling apply, the function receives a Series for each group instead of a DataFrame. This is simpler when the logic needs only one column.
spread = df.groupby("region")["revenue"].apply(lambda s: s.max() - s.min())
print(spread)
# region
# North 25.0
# South 90.0
# Name: revenue, dtype: float64The SeriesGroupBy version does not need include_groups because the function never sees the grouping column.
Edge cases to know
- Mixed return types. If some groups return a scalar and others return a Series, pandas cannot combine them cleanly. The result is usually an object-dtype Series or an error. Make every code path return the same kind of object.
- Empty or all-missing groups. Your function still runs on groups whose values are all
NaN. Methods like.idxmax()behave differently with missing data across pandas versions, so test with such groups when your data can contain them. - Group keys that are missing. Rows with a missing key are dropped before
applyruns unless you passdropna=Falsetogroupby. - Same-index results. If the function returns something indexed identically to its input, the result lines up with the original rows. With
group_keys=True, the keys are still added as an extra index level. Usetransformwhen you want the original index with no surprises. - Side effects. Do not rely on how many times the function is called or on the order of calls. Older pandas versions called the function twice on the first group in some cases. Write functions that are pure and free of side effects.
Performance
apply calls your Python function once per group. For a few groups this is fine. For hundreds of thousands of groups, the overhead of constructing a DataFrame or Series for each group dominates the runtime. Built-in aggregations like sum and mean run in compiled code and avoid this cost.
Compare these two ways to get the total revenue per region. They return the same values, but the second is much faster on large data.
slow = df.groupby("region").apply(lambda g: g["revenue"].sum(), include_groups=False)
fast = df.groupby("region")["revenue"].sum()Many "custom" tasks have a vectorized form. The top-1 example above can use idxmax, which finds the row label of the largest value in each group, and then select those rows with .loc.
top_rows = df.loc[df.groupby("region")["revenue"].idxmax()]
print(top_rows)
# region product units revenue
# 0 North A 10 100.0
# 4 South B 8 120.0For top-N, sorting once and then taking head(n) per group also avoids a Python function call per group:
top_two_fast = df.sort_values("revenue", ascending=False).groupby("region").head(2)Common errors
- Reading the grouping column after
include_groups=False. The code raises aKeyErrorfor"region". Useg.nameinstead. - Forgetting
group_keys=False. The result has an unexpected MultiIndex, and later joins or.loclookups on the original labels fail. - Using
applyfor plain aggregation. It works, but it is slower thanaggand hides intent. - Returning inconsistent shapes. Different groups returning different types produce an object-dtype result that is hard to work with.
Exercise
Write a groupby call that returns, for each region, the two rows with the most units. Keep the original row labels as the index and do not add the region as an index level. Then name a faster alternative that avoids calling a Python function per group.
Show answer
Use apply with groupkeys=False and includegroups=False: df.groupby("region", groupkeys=False).apply(lambda g: g.nlargest(2, "units"), includegroups=False) This returns rows 0 and 1 for North and rows 4 and 2 for South, with their original labels, and without the region column. A faster alternative is df.sort_values("units", ascending=False).groupby("region").head(2), which sorts once and takes the first two rows of each group. It keeps the region column and orders rows by units rather than by group.