Sub topic 13
Adding group statistics with transform
This chapter assumes you can build a DataFrame, select a column by name, and use groupby for basic aggregation. It covers how to attach a group-level statistic to every row of the original DataFrame.
Why aggregation is not enough
A normal groupby(...).sum() returns one row per group. Suppose you want each sale's share of its region's total. You need the regional total next to every row, so the result must have the same length as the original frame.
transform does this. It computes a function per group, then returns a result aligned to the original index. Each row gets the value for its own group.
A worked example
import pandas as pd
sales = pd.DataFrame({
"region": ["N", "N", "S"],
"amount": [10, 30, 20],
})
sales["region_total"] = sales.groupby("region")["amount"].transform("sum")
sales["region_share"] = sales["amount"] / sales["region_total"]
print(sales)The output is:
region amount region_total region_share
0 N 10 40 0.25
1 N 30 40 0.75
2 S 20 20 1.00Rows 0 and 1 both receive 40, the total for region N. No merge is needed, and the original row order is preserved.
Common uses
You can pass a built-in name such as "sum", "mean", "max", "count" or "rank", or you can pass a function. A lambda lets you compute a per-group transformation, such as centering values on the group mean.
sales["centered"] = sales.groupby("region")["amount"].transform(
lambda s: s - s.mean()
)
sales["rank_in_region"] = sales.groupby("region")["amount"].transform("rank")
print(sales[["region", "amount", "centered", "rank_in_region"]])Prefer string names where possible. pandas runs them with optimized code, while a lambda runs once per group in Python and is slower on data with many groups.
What transform must return
The function you pass must produce either a single value per group, which pandas broadcasts to every row of that group, or a result with the same length as the group. A result of any other length raises an error.
| Function returns | Result |
|---|---|
| One scalar per group (`"sum"`, `"mean"`) | Value repeated for each row in the group |
| Same-length Series (`s - s.mean()`) | Row-by-row values aligned to the original index |
| Different length (`s.head(1)`) | Error |
Gotchas
- Select the column first.
sales.groupby("region").transform("sum")transforms every non-key column. Choose["amount"]to get a single Series you can assign. - Missing group keys. By default
groupbydrops rows whose key isNaN. Those rows getNaNin the transformed column. Passdropna=Falsetogroupbyif you want them treated as their own group. - Missing values in the data.
"sum"and"mean"skipNaNinside a group. A group whose values are allNaNyields0for"sum"andNaNfor"mean". - Choose transform, not apply, for alignment.
applymay return a differently shaped result.transformguarantees alignment with the original rows.
Exercise
A DataFrame df has columns team and score. Write one line that adds a column score_vs_team_max holding each row's score divided by the highest score on that row's team.
Show answer
df["scorevsteam_max"] = df["score"] / df.groupby("team")["score"].transform("max")
Exercise
Why does df.groupby("team")["score"].agg("mean") fail to work as a new column when assigned directly with df["avg"] = ..., while transform("mean") works?
Show answer
agg returns one row per team, indexed by team name, so it does not align with the original row index and the assignment produces NaN or mismatched values. transform("mean") returns a Series with the original index and length, so each row receives its own team's mean.