Sub topic 13
Adding group statistics with transform
This chapter assumes you can build a DataFrame, select columns by name, assign new columns with df["name"] = ..., and have a rough idea of what groupby does. You do not need to know merge well, though the chapter mentions it for comparison.
The problem: group numbers on every row
Often you want each row to know something about its group. Examples are a sale's share of its region's total, a temperature minus its city's average, or a flag marking the best rep in each team.
A plain groupby(...).sum() gives one row per group. You can't assign that result back as a column, because it has fewer rows than the original. transform solves this. It computes the statistic per group and returns a Series with the same index and length as the original, so each row receives its group's value.
agg, transform, and apply compared
All three run on a groupby object, but they return different shapes.
| Method | Typical result shape | Use it when |
|---|---|---|
| `agg` | One row per group | You want a summary table |
| `transform` | Same length and index as the input | You want a new column on the original rows |
| `apply` | Depends on what your function returns | Your logic doesn't fit the other two |
Here is the difference on a small table.
import pandas as pd
sales = pd.DataFrame({
"region": ["N", "N", "S", "S", "S"],
"rep": ["ann", "bob", "cy", "di", "ed"],
"amount": [10.0, 30.0, 20.0, 50.0, 80.0],
})
g = sales.groupby("region")["amount"]
print(g.sum()) # 2 rows: N -> 40.0, S -> 150.0
print(g.transform("sum")) # 5 rows: 40.0, 40.0, 150.0, 150.0, 150.0The first result has index N, S. The second keeps the index 0 to 4, so it lines up with sales and you can assign it directly:
sales["region_total"] = g.transform("sum")
sales["share"] = sales["amount"] / sales["region_total"]
print(sales)Because transform returns an ordinary Series aligned to the original rows, you can use it inside any vectorized expression. You don't need an intermediate table or a merge.
Built-in names versus functions
transform accepts a string naming a built-in aggregation: "sum", "mean", "median", "min", "max", "std", "count", "size", "first", "last", "nunique". It also accepts a function or lambda.
sales["region_mean"] = g.transform("mean")
sales["region_max"] = g.transform("max")
sales["vs_mean"] = sales["amount"] - sales["region_mean"]
sales["is_top"] = sales["amount"] == sales["region_max"]
sales["pct_of_max"] = sales["amount"] / sales["region_max"]A lambda lets you write logic that isn't a built-in. A group z-score is a common case:
sales["z_slow"] = g.transform(lambda s: (s - s.mean()) / s.std())This works, but pandas calls the lambda once per group in Python. With many groups it is slow. The version below gives the same result using only vectorized pieces:
sales["z"] = (sales["amount"] - g.transform("mean")) / g.transform("std")Prefer string names where you can, and combine them with ordinary arithmetic. Reserve lambdas for logic that really needs the whole group at once.
Methods that already return same-length results
Some groupby methods already return one value per original row. They need no transform:
cumsum(),cumcount(),cummax()rank()shift(),diff(),pct_change()ffill(),bfill()
sales["rank_in_region"] = g.rank(ascending=False)
sales["running_total"] = g.cumsum()
sales["prev_amount"] = g.shift(1)Use transform when you are reducing a group to one number and want that number repeated on every row. Use these methods when the result is naturally per row.
Filling missing values with group statistics
A common use is filling gaps with a value that is typical for the row's group instead of for the whole column.
temps = pd.DataFrame({
"city": ["A", "A", "A", "B", "B"],
"temp": [10.0, None, 14.0, 20.0, None],
})
city_mean = temps.groupby("city")["temp"].transform("mean")
temps["temp_filled"] = temps["temp"].fillna(city_mean)
print(temps)City A's mean is 12.0 and city B's is 20.0, so temp_filled is 10.0, 12.0, 14.0, 20.0, 20.0. The group mean skips NaN by default, so a missing value does not spoil the statistic. fillna accepts a Series and matches it to the column by index, which works here because transform preserved the index.
Edge cases that change the result
count versus size
"count" counts non-missing values in the column. "size" counts all rows in the group.
temps["n_valid"] = temps.groupby("city")["temp"].transform("count")
temps["n_rows"] = temps.groupby("city")["temp"].transform("size")For city A, n_valid is 2 and n_rows is 3. If you want the share of rows that have data, divide one by the other.
Rows whose group key is missing
By default, groupby drops rows whose key is NaN or None. With transform, those rows are not dropped from the output. They get NaN as their result.
d = pd.DataFrame({"key": ["a", None, "a", None], "v": [1, 2, 3, 4]})
d["default"] = d.groupby("key")["v"].transform("sum")
d["kept"] = d.groupby("key", dropna=False)["v"].transform("sum")
print(d)The default column is 4.0, NaN, 4.0, NaN. The kept column is 4, 6, 4, 6, because dropna=False treats missing keys as their own group. Choose based on what a missing key means in your data.
Grouping by several keys
Pass a list to group on a combination of columns. Each row gets the statistic of its exact combination.
orders = pd.DataFrame({
"region": ["N", "N", "N", "S"],
"year": [2025, 2025, 2026, 2026],
"amount": [5, 15, 40, 8],
})
orders["region_year_total"] = (
orders.groupby(["region", "year"])["amount"].transform("sum")
)The totals are 20, 20, 40, 8.
Single-row groups
A group of one row has no sample standard deviation, so "std" returns NaN for it. A z-score for that row is then NaN too. Check for it if singleton groups are possible.
Wrong output length
A function passed to transform must return either a single value (which is broadcast) or a result with the same length as its group. Anything else raises a ValueError. If you need to return a different length, you want apply or agg instead.
Using transform in a method chain
Because the expression only needs the frame as built so far, transform fits inside assign():
result = (
sales[["region", "rep", "amount"]]
.assign(
region_total=lambda d: d.groupby("region")["amount"].transform("sum"),
share=lambda d: d["amount"] / d["region_total"],
)
)The second lambda can use region_total because assign evaluates its arguments in order.
transform versus agg plus merge
You can get the same effect by aggregating, then merging back on the key:
totals = (
sales.groupby("region", as_index=False)["amount"]
.sum()
.rename(columns={"amount": "region_total"})
)
merged = sales[["region", "rep", "amount"]].merge(totals, on="region", how="left")This is longer and needs a join key. It can also change the row order or the index. transform keeps the original order and index with one line, so prefer it for adding a single group statistic to the existing rows. Use the merge approach when you already have a summary table that you need for other purposes.
Exercise
A DataFrame df has columns team and score. Write one line that adds a column score_vs_team holding each score minus the mean score of that row's team. Why does this use transform("mean") and not agg("mean")?
Show answer
df["score_vs_team"] = df["score"] - df.groupby("team")["score"].transform("mean"). agg("mean") returns one row per team, so its length and index don't match df. transform("mean") repeats each team's mean on every row of that team, in the original order, so the subtraction works element by element.
Exercise
In a column price grouped by shop, some prices are missing. You want to fill each missing price with the median of its own shop. Write the code. Then explain what happens to rows whose shop value is itself missing, and how to change that.
Show answer
df["price"] = df["price"].fillna(df.groupby("shop")["price"].transform("median")). Rows with a missing shop are left out of every group, so transform returns NaN for them and fillna has nothing to fill with. Passing dropna=False to groupby makes missing shop values form their own group, and those rows then get that group's median.