Sub topic 15
Adding group statistics to each row with transform
This chapter assumes you can build a DataFrame, select columns, and use groupby with agg. Here you will add a per-group statistic to every original row.
Why transform exists
groupby(...).agg(...) returns one row per group. That is a summary, but you often need the group statistic next to each original row. For example, you might want each order's share of its region's total.
transform runs the same group calculation and then returns a result with the same length and index as the original data. Each row receives the value for its own group.
Computing each row's share of its group
The example below uses the sales DataFrame from earlier chapters.
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],
})
df["region_share"] = df["units"] / df.groupby("region")["units"].transform("sum")
print(df[["region", "units", "region_share"]])The output is:
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.466667The transform("sum") call returns a Series of six values: 10, 17, 10, 15, 17, 15. It lines up with df by index, so ordinary division works row by row. Notice that North's total is 10, because sum skips the missing value. The row with the missing value stays NaN.
Passing a function
You can give transform a string such as "mean", "max" or "count". You can also give it a function that takes each group's Series and returns either one value or a Series of the same length.
df["units_vs_region_avg"] = df["units"] - df.groupby("region")["units"].transform("mean")
df["units_centered"] = df.groupby("region")["units"].transform(lambda s: s - s.mean())
print(df[["region", "units", "units_vs_region_avg", "units_centered"]])Both new columns hold the same numbers. Prefer the string form when one exists. It uses pandas' built-in group operations, which are usually faster than calling a Python function once per group.
Filling missing values with a group statistic
Because the result keeps the original index, transform works well with fillna. This replaces each missing value with the mean of its own region:
group_mean = df.groupby("region")["units"].transform("mean")
df["units_filled"] = df["units"].fillna(group_mean)
print(df[["region", "units", "units_filled"]])The missing North value becomes 10.0, the mean of North's one known value.
Common errors
- Using
aggand expecting aligned rows.agg("sum")returns a shorter result indexed by group. Assigning it to a column givesNaNor a mismatch. Usetransformwhen you need a value on every row. - A function that changes the length. A function passed to
transformmust return a scalar or a result the same length as the group. Returning a filtered or sorted subset raises an error. - Rows whose group key is missing.
groupbydropsNaNkeys by default (dropna=True). Those rows getNaNfromtransform. Passdropna=Falseto keep them as their own group.
Exercise
Using the sales DataFrame, add a column max_in_region that holds the largest units value in each row's region. Which method do you use, and what value does the South row with 5 units get?
Show answer
Use df["max_in_region"] = df.groupby("region")["units"].transform("max"). South has units 5 and 12, so both South rows get 12.0.