Sub topic 10
Group-wise values on every row with transform
This chapter assumes you can run a basic groupby(...).agg(...) call and that you know how pandas aligns a Series to a DataFrame by index label.
Why aggregation is not always enough
An aggregation such as sum collapses each group to one row. Sometimes you need the group result next to the original rows. Examples are each row's share of its group total, or its distance from the group average.
transform does this. It computes a value per group, then broadcasts it back so the output has the same index and length as the input.
Computing a share of the group total
The example below divides each row's revenue by its region's total.
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],
})
df["revenue_share"] = df["revenue"] / df.groupby("region")["revenue"].transform("sum")
print(df[["region", "revenue", "revenue_share"]])
# region revenue revenue_share
# 0 North 100.0 0.571429
# 1 North 75.0 0.428571
# 2 South 70.0 0.318182
# 3 South 30.0 0.136364
# 4 South 120.0 0.545455The transform("sum") result has five values: 175.0 for the two North rows and 220.0 for the three South rows. Because its index matches df, the division works row by row.
Passing a function
transform accepts a string naming a built-in, such as "sum", "mean", "max", or "rank". It also accepts any callable. A callable receives each group's column as a Series. It must return either a Series of the same length or a single value, which pandas broadcasts.
import pandas as pd
sales = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
grouped = sales.groupby("region")["revenue"]
# Distance from the group mean
sales["vs_mean"] = (sales["revenue"] - grouped.transform("mean")).round(2)
# Z-score within each group (sample standard deviation)
sales["zscore"] = grouped.transform(lambda s: (s - s.mean()) / s.std()).round(2)
print(sales)String names use optimized code paths. A lambda runs once per group in Python, so prefer the string form when one exists.
Common errors
The first error is assigning an aggregation to a column. agg and sum return one row per group, indexed by the group key. Assigning that result to a column aligns on the index, and the labels do not match.
df["total"] = df.groupby("region")["revenue"].sum()
# Every value in df["total"] is NaN, because the index
# labels "North" and "South" do not match the row labels 0 to 4.Use transform("sum") instead.
The second error is a function that changes the length. A callable passed to transform must return a Series with the same length as its group, or a scalar. Dropping rows or returning a different number of values raises an error. To drop whole groups, use filter, which a later chapter covers.
The third error is expecting access to several columns at once. transform calls your function on one column at a time. If a calculation needs two columns together, use apply, which a later chapter covers.
Choosing between agg and transform
| Need | Method | Output rows |
|---|---|---|
| Summary table | `agg` | One per group |
| New column on the original data | `transform` | One per input row |
Exercise
Using the sales DataFrame above, write one line that adds a column is_top that is True for the row holding the maximum revenue in its region.
Show answer
sales["is_top"] = sales["revenue"] == sales.groupby("region")["revenue"].transform("max")