Sub topic 15
Adding group statistics to each row with transform
groupby(...).agg(...) shrinks the data to one row per group. Sometimes you want the group statistic next to every original row instead, for example to compute each order's share of its region's total. transform does this: it computes a per-group result and returns it aligned to the original rows.
This chapter assumes you can build a DataFrame, select columns, and have read the earlier chapters on groupby and named aggregation. It uses the sales DataFrame from earlier in the tutorial.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})Aggregate versus transform
Both methods split rows by group and apply a function to each piece. They differ in the shape of the result.
Here is the same sum computed both ways:
print(df.groupby("region")["units"].agg("sum"))
df["region_total"] = df.groupby("region")["units"].transform("sum")
print(df[["region", "units", "region_total"]])The first call returns a Series of three values indexed by region. The second returns six values indexed 0 to 5, so it can be assigned straight to a new column:
region units region_total
0 North 10.0 10.0
1 South 5.0 17.0
2 North NaN 10.0
3 East 8.0 15.0
4 South 12.0 17.0
5 East 7.0 15.0Rows 0 and 2 are both North, so both show 10.0. The missing value in row 2 was skipped when summing, which matches the behaviour of sum in ordinary aggregation.
Computing each row's share of its group
Once the group total sits on every row, ordinary arithmetic gives the share. You can also skip the helper column:
df["region_share"] = df["units"] / df.groupby("region")["units"].transform("sum")
print(df[["region", "units", "region_share"]]) region units region_share
0 North 10.0 1.000000
1 South 5.0 0.294118
2 North NaN NaN
3 East 8.0 0.533333
4 South 12.0 0.705882
5 East 7.0 0.466667Division works because both sides have the same index. transform guarantees this alignment, which is why it is safer than computing a grouped agg and merging it back by hand.
The missing row gets a missing share. The shares of the non-missing rows in each region still add up to 1.
Common uses
Four patterns cover most real uses.
- Share of group:
value / transform("sum"), as above. - Distance from the group average:
value - transform("mean"). - Filling gaps with a group value:
fillna(transform("mean")). - Scaling within a group:
value / transform("max").
group_mean = df.groupby("region")["units"].transform("mean")
df["units_vs_avg"] = df["units"] - group_mean
df["units_filled"] = df["units"].fillna(group_mean)
print(df[["region", "units", "units_vs_avg", "units_filled"]])North's mean is 10.0, South's is 8.5 and East's is 7.5. Row 2 therefore gets a filled value of 10.0, and row 1 gets 5 − 8.5 = −3.5 as its distance from the average.
Reusing group_mean avoids running the group computation twice.
What functions transform accepts
transform takes three kinds of argument:
- A string naming a built-in:
"sum","mean","max","min","count","size","first","last","median","std","nunique". Pandas has optimised code for these, so use them when you can. - A function: it receives each group's column as a Series.
- A list or dict of functions: support exists for DataFrame-level calls, but beginners rarely need it.
A custom function must return either a scalar, which pandas repeats for every row in the group, or a sequence with the same length as the group. Any other length raises an error.
df["share_of_max"] = df.groupby("region")["units"].transform(lambda s: s / s.max())
print(df[["region", "units", "share_of_max"]])This lambda returns a Series the same length as its group, so each row is divided by the maximum for its region. South gives 5/12 = 0.416667 and 12/12 = 1.0.
Custom functions run once per group in Python, which is much slower than a string name when you have many groups. Prefer the "max" string with vectorised arithmetic, as in df["units"] / df.groupby("region")["units"].transform("max"), when speed matters.
Some grouped methods already return one value per row, so you can call them without transform. Ranking inside groups is the usual example:
df["rank_in_region"] = df.groupby("region")["units"].rank(ascending=False)This ranks each row among its own region's rows, with 1 for the largest. It follows the same alignment rule as transform.
Missing values and transform
Missing values appear in two places, and they behave differently.
Missing values in the column being summarised are skipped by default, as you saw with North's total. The row itself still receives the group statistic. Row 2 shows region_total of 10.0 even though its own units is missing. If you compute a share from it, the result is missing because the numerator is missing.
Missing values in the grouping column are the more surprising case. By default, groupby drops rows whose key is missing. For transform, those rows are kept in the output but receive a missing value:
d2 = pd.DataFrame({"g": ["a", None, "a"], "v": [1, 2, 3]})
print(d2.groupby("g")["v"].transform("sum"))
print(d2.groupby("g", dropna=False)["v"].transform("sum"))The first call gives 4.0, NaN, 4.0. The second treats the missing key as its own group and gives 4.0, 2.0, 4.0. Pass dropna=False when rows with an unknown key should still get a group statistic.
You can control whether missing data inside a column is skipped with a lambda, for example lambda s: s.sum(skipna=False). Under that rule, North's total becomes missing because one of its values is missing.
Transform and sorting
transform does not reorder anything. The result always has the same index and order as the input, whatever order the groups are discovered in. That makes it safe to combine with the sorting tools from earlier chapters. For example, you can put the biggest regional orders first:
result = df.assign(
region_total=df.groupby("region")["units"].transform("sum")
).sort_values(["region_total", "units"], ascending=[False, False])
print(result[["region", "units", "region_total"]])South (total 17) comes first, then East (15), then North (10). Within each region, larger units values come first, and North's missing value is placed last by the default na_position.
This is a case where sorting by a group statistic is only possible with transform. A grouped agg has one row per region, so it has nothing to sort the original rows by.
Choosing between agg, transform and pivot_table
| You need | Use |
|---|---|
| One row per group | `groupby(...).agg(...)` |
| The group statistic on every original row | `groupby(...).transform(...)` |
| A grid of groups by categories | `pivot_table` |
If you find yourself running agg, then merge back onto the original table, replace it with transform. It is shorter and cannot misalign rows.
Common errors
- Passing a named aggregation to transform. The
name=("col", "func")syntax works only withagg.transformtakes one function per call. - Returning the wrong length. A function that returns a different number of values than the group has rows raises a
ValueError. Collapsing functions such aslambda s: s.nlargest(2)fall into this trap. - Assigning an
aggresult as a column. Assigning a three-row Series indexed by region to a six-row DataFrame aligns on the wrong index and fills the column with NaN. Usetransform, or map the result by region explicitly. - Expecting integers. A column with missing values is float, and a mean is a float. Totals of integer columns without missing values stay integer.
Exercise
Add a column product_share to df that gives each row's units as a fraction of the total units for the same product (not the region). Which rows have a missing value in the new column, and why?
Show answer
Use df["product_share"] = df["units"] / df.groupby("product")["units"].transform("sum"). Product A has units 10, 8 and 12 (total 30), and product B has 5, NaN and 7 (total 12). Row 2 is the only row with a missing share, because its own units value is missing, so the numerator is NaN. The other B rows get 5/12 and 7/12, and the A rows get 10/30, 8/30 and 12/30.
Exercise
A DataFrame has a team column in which some entries are missing. You call df.groupby("team")["score"].transform("mean") and find NaN in the result for those rows. How do you give those rows a mean calculated across all rows with a missing team?
Show answer
Pass dropna=False to groupby: df.groupby("team", dropna=False)["score"].transform("mean"). The rows with missing team then form their own group, and each receives that group's mean.