Sub topic 10
Group-wise values on every row with transform
This chapter assumes you can build a DataFrame, select columns, and use groupby(...)[col].sum() as covered earlier. It also assumes you know that a pandas Series carries an index. Here you will learn how transform returns group-level results while keeping the original rows, and when to use it in place of agg.
Aggregation shrinks, transform preserves
An aggregation such as sum collapses each group to one value. The result has one row per group. That is the right shape for a summary table. It is the wrong shape when you want to put a group-level number next to each original row, for example to compute each row's share of its group total.
transform computes a group-wise result and returns it with the same index as the input. Every row gets a value, and rows in the same group receive values computed from that group.
A first example: share of the group total
The sample data used throughout this chapter has five rows, two regions, and two products.
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 expression df.groupby("region")["revenue"].transform("sum") yields a Series of length 5: 175.0, 175.0, 220.0, 220.0, 220.0. Because it shares the index of df, you can divide df["revenue"] by it directly. No merge or join is needed.
The same result with agg takes two steps. You compute the totals, then look each row's region up in them:
totals = df.groupby("region")["revenue"].sum()
share = df["revenue"] / df["region"].map(totals)This works, but it makes you manage the alignment yourself. transform does that for you.
What a transform function may return
transform accepts a string naming a built-in method, such as "sum", "mean", "max", "nunique", or "rank". It also accepts a callable. For each group, the function must produce one of two things:
- A scalar. pandas broadcasts it to every row of that group. This is the case for
"sum"and"mean". - A sequence or Series with the same length as the group. pandas places the values back at the group's original row positions.
If a function returns something else, such as a shorter Series, pandas raises a ValueError. Whatever the function returns, the final result lines up with the original rows, in the original order. The order of the groups does not change it.
Standardizing within each group
A z-score subtracts the group mean from each value and divides by the group standard deviation. A callable that returns a same-length Series is a natural fit:
z = df.groupby("region")["units"].transform(lambda s: (s - s.mean()) / s.std())
print(z)
# 0 0.707107
# 1 -0.707107
# 2 0.377964
# 3 -1.133893
# 4 0.755929
# Name: units, dtype: float64Inside the lambda, s is the units values of one region. Each group is standardized against its own mean and its own standard deviation. Series.std() uses ddof=1 by default, so the values match the sample standard deviation.
Filling missing values with a group statistic
Group-wise imputation is one of the most common uses of transform. Here a missing score is replaced by the mean of that team's scores:
import numpy as np
import pandas as pd
scores = pd.DataFrame({
"team": ["x", "x", "x", "y", "y"],
"score": [10.0, np.nan, 20.0, 5.0, 7.0],
})
group_mean = scores.groupby("team")["score"].transform("mean")
scores["filled"] = scores["score"].fillna(group_mean)
print(scores)
# team score filled
# 0 x 10.0 10.0
# 1 x NaN 15.0
# 2 x 20.0 20.0
# 3 y 5.0 5.0
# 4 y 7.0 7.0The group mean skips missing values by default. Team x has a mean of 15.0, computed from 10.0 and 20.0. fillna accepts a Series and matches it to scores["score"] by index, which is why the aligned result of transform is so convenient.
Methods that already behave like transforms
Some GroupBy methods return one value per input row without being called through transform. These include cumsum, cumcount, shift, diff, rank, and pct_change. They preserve the original index in the same way.
df["running_revenue"] = df.groupby("region")["revenue"].cumsum()
print(df["running_revenue"])
# 0 100.0
# 1 175.0
# 2 70.0
# 3 100.0
# 4 220.0
# Name: running_revenue, dtype: float64Use these methods directly when one exists. They need no wrapper and they are fast. Use transform when you need a reduction broadcast back to the rows (sum, mean, max, nunique) or custom logic that has no built-in method.
Transforming several columns
Select a list of columns to get a DataFrame back with the same shape as the selection:
cols = df.groupby("region")[["units", "revenue"]].transform("sum")
print(cols)
# units revenue
# 0 15 175.0
# 1 15 175.0
# 2 18 220.0
# 3 18 220.0
# 4 18 220.0Select the columns explicitly. If you call df.groupby("region").transform("sum") on the whole frame, it also tries to sum product. For strings, sum concatenates them, which is rarely what you want. For other functions it may raise an error. The grouping column itself is not part of the result.
Choosing between transform and its neighbors
The decision comes down to the shape you need out.
| Method | Output shape | Typical use |
|---|---|---|
| `agg` | One row per group | Summary tables |
| `transform` | Same length and index as the input | Normalization, shares, group-wise imputation |
| `filter` | A subset of the original rows | Keeping or dropping whole groups |
| `apply` | Depends on what the function returns | Custom logic that fits none of the above |
The next chapters cover filter and apply. A common pattern is to combine transform with ordinary boolean indexing. This keeps the rows whose revenue is above their group's average:
above_avg = df[df["revenue"] > df.groupby("region")["revenue"].transform("mean")]
print(above_avg[["region", "revenue"]])
# region revenue
# 0 North 100.0
# 4 South 120.0North's mean is 87.5 and South's is 73.33, so only rows 0 and 4 pass. The row-level condition is evaluated against a group-level value, which is hard to express with agg alone.
Gotchas
Speed: strings beat lambdas
When you pass a string such as "sum" or "mean", pandas can use an optimized path that runs over all groups at once. When you pass a lambda, pandas calls your Python function once per group. With thousands of groups, the lambda version can be many times slower. Prefer the string form when a built-in exists. If you need a custom formula, compute its pieces with string transforms and combine them with vectorized arithmetic:
g = df.groupby("region")["units"]
z_fast = (df["units"] - g.transform("mean")) / g.transform("std")This gives the same values as the lambda version above, and it avoids a Python call per group.
Missing group keys
Rows whose group key is missing are excluded from the groups when dropna=True, which is the default. The result still has to cover every input row. In recent pandas versions, those rows receive NaN in the transformed output. If you want them treated as their own group, pass dropna=False to groupby. Check the behavior on your installed version before relying on it.
Functions that depend on the whole group
A callable passed to transform sees one group at a time. It cannot see the other groups. A function that needs global information, such as the overall mean, should get it from outside the lambda. Compute that value first, then use it in the lambda or in vectorized arithmetic.
Result type
transform("sum") preserves the input's dtype where it can. Integer columns stay integer, as the units totals above show. A callable may change the dtype, for example from integer to float when it divides. Check .dtype if a downstream step depends on it.
Exercise
Add a column units_vs_region_avg to df that holds each row's units minus the average units of its region. What values do you expect for the five rows?
Show answer
Use transform to broadcast the group mean, then subtract it: df["unitsvsregion_avg"] = df["units"] - df.groupby("region")["units"].transform("mean") North's mean is 7.5 and South's is 6.0, so the values are 2.5, -2.5, 1.0, -3.0, 2.0 for rows 0 to 4.
Exercise
A teammate writes df.groupby("region")["revenue"].transform(lambda s: s.sum()) on a 100,000-row frame with 50,000 regions and finds it slow. What change would you make, and why does it help?
Show answer
Replace the lambda with the string form, transform("sum"). The string lets pandas use its optimized grouped implementation instead of calling a Python function once for each of the 50,000 groups. The result is the same.