Sub topic 12
Custom logic with apply
This chapter assumes you can use groupby with agg, transform, and filter, and that you know how to build a DataFrame and select columns. When none of those fit, apply runs any function you write on each group.
What apply does
apply splits the data, then calls your function once per group. The function receives the group as a DataFrame. pandas then combines the results, and the shape of the output depends on what your function returns.
| Function returns | Result |
|---|---|
| A scalar | A Series with one value per group |
| A Series | A DataFrame with one row per group |
| A DataFrame | Rows stacked, with the group keys added to the index |
Returning a scalar
Start with a result that agg cannot compute directly. This is the units-weighted average of revenue per unit.
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],
})
def weighted_price(g):
return (g["revenue"] * g["units"]).sum() / g["units"].sum()
result = df.groupby("region").apply(weighted_price, include_groups=False)
print(result)
# region
# North 91.666667
# South 85.555556
# dtype: float64The include_groups=False argument needs pandas 2.2 or later. It leaves the grouping column out of each group. Without it, pandas 2.2 and later emit a DeprecationWarning, because a later version will stop passing the grouping columns to the function.
Returning a Series
If the function returns a Series, its index labels become the output columns.
def spread(g):
return pd.Series({
"top_revenue": g["revenue"].max(),
"revenue_range": g["revenue"].max() - g["revenue"].min(),
})
print(df.groupby("region").apply(spread, include_groups=False))
# top_revenue revenue_range
# region
# North 100.0 25.0
# South 120.0 90.0Returning a DataFrame
A function can also return several rows per group, for example the best row of each group. In that case pandas stacks the pieces, and the group key becomes the outer level of a MultiIndex.
top = df.groupby("region").apply(
lambda g: g.nlargest(1, "revenue"), include_groups=False
)
print(top.index.tolist())
# [('North', 0), ('South', 4)]Call reset_index(level=0) or pass group_keys=False to groupby if you do not want the key in the index.
Choosing between the methods
Reach for apply last. Work down this list and stop at the first match:
- Use
aggwhen each group reduces to one row and a built-in function exists. - Use
transformwhen you need one value per original row. - Use
filterwhen you want to keep or drop whole groups. - Use
applywhen the logic needs several columns at once, or when the output shape varies.
Common errors
- Inconsistent return types. If the function returns a scalar for some groups and a Series for others, the result is unpredictable. Return the same type for every group.
- Missing grouping column. With
include_groups=False, the function cannot readg["region"]. Compute anything that needs the key beforehand. - Unexpected extra index level. A function that returns a DataFrame produces a MultiIndex. This is normal, so reset it or set
group_keys=False.
Exercise
A function passed to groupby("region").apply(...) returns a pandas Series with the labels "low" and "high" for each group. What does the result look like?
Show answer
A DataFrame with one row per region (the index is the region) and two columns, "low" and "high".