Knowledge base / Python
pandas transform: a group mean beside every row
I use six records to add group means, explain the standardisation arithmetic and identify groups without a defined result.

When I need to compare a row with its group’s mean, I use groupby(...).transform(...). I want a group statistic beside every observation without assembling the result from a separate summary table. My first question is whether the reader needs one row per group or still one row per observation.
This reference focuses on SeriesGroupBy.transform: operating on a selected column after grouping. The data is synthetic and the explanation follows pandas 3.1.1 documentation. I am not extending the same shape promise to every multi-function variant of DataFrame.transform.
Return the group mean to each row
SeriesGroupBy.transform returns a Series indexed like the input. A function can return a suitably sized result or a scalar broadcast across the group. For a simple operation, I use its name:
import pandas as pd
sales = pd.DataFrame({
"region": ["A", "B", "A", "B", "A", "B"],
"amount": [100, 300, 150, 400, 200, 500],
})
sales["group_mean"] = sales.groupby("region")["amount"].transform("mean")
sales["difference"] = sales["amount"] - sales["group_mean"]
| Index | Region | Amount | Group mean | Difference |
|---|---|---|---|---|
| 0 | A | 100 | 150.0 | -50.0 |
| 1 | B | 300 | 400.0 | -100.0 |
| 2 | A | 150 | 150.0 | 0.0 |
| 3 | B | 400 | 400.0 | 0.0 |
| 4 | A | 200 | 150.0 | 50.0 |
| 5 | B | 500 | 400.0 | 100.0 |
For A, add 100, 150 and 200, then divide by three. Repeat with 300, 400 and 500 for B. The means are 150 and 400. The interleaved input is deliberate: the statistic belongs beside its original observation, rather than creating an A block followed by a B block.
Use aggregation when a summary is enough
If I only need two means, I use sales.groupby("region")["amount"].mean(). It returns one value for A and one for B. transform("mean") answers a different question: which mean belongs beside each of six records? The grouping guide distinguishes aggregation from transformation. I choose the output level before adding columns to the dataset.
Avoid assigning a summary Series indexed by region names directly to a frame indexed by numbers while expecting a match through the region column. Those are different index labels. A separate summary needs explicit, correct matching. transform simplifies this particular use case. It does not replace arbitrary joins or every custom operation possible with apply.

Make ddof explicit when standardising
Using the same input, add the group standard deviation and standardised value:
grouped = sales.groupby("region")["amount"]
sales["group_std"] = grouped.transform("std", ddof=1)
sales["z"] = sales["difference"] / sales["group_std"]
The std reference specifies default ddof=1, using a divisor one below the observation count. A’s deviations are -50, 0 and 50. Their squared sum is 5000; divide by two and take the square root to obtain 50. B similarly gives 100. The successive z values are therefore -1, -1, 0, 0, 1, 1.
Changing the divisor to the observation count changes the result. ddof=0 represents a different calculation. The previous text mixed conventions and showed incorrect values. I use symmetric groups here so you can follow the arithmetic without random inputs. Standardisation alone also cannot establish that comparing two regions is commercially fair. Market size and other conditions require separate investigation.
Handle constant groups and absent keys
A group with one observation has insufficient data for standard deviation with ddof=1. Constant values give a standard deviation of zero. Decide how to handle these groups before using a ratio. A missing result may indicate an undefined measure for the case, rather than a programming error. I would not replace it with zero automatically: zero already has a particular meaning in a standardised measure.
By default, groupby excludes missing grouping keys. If an absent region should form its own group, the documentation describes dropna=False. That differs from excluding absent amounts when calculating a mean. Both keys and amounts are complete in this example. For a real source, I would review these two kinds of missing data separately before interpreting differences.
Check what the result means
Establish what a row represents. If it is an order line, averaging lines answers a different question from averaging orders. transform retains observations but cannot repair a measure’s definition. I would document the data level beside the result column. Avoid using the mean to assess people or regions before checking that the underlying cases are actually comparable.
For an exercise, change the first amount from 100 to 250. Which rows need a new mean? All three A rows do, while B is unaffected. Explain why changing one record affects the statistic beside the other records in its group. If your task only requires replacing codes with descriptions, return to the simpler pandas map instead of introducing unnecessary grouping.
Key takeaways
Does transform reduce the result to one row per group?
The SeriesGroupBy.transform shown here returns values aligned to input observations. Aggregating mean instead returns one value per group.
Which ddof does pandas std use?
The default ddof=1 uses N-1 as the divisor. The example groups have standard deviations of 50 and 100.
Can every group be standardised?
A singleton is insufficient with ddof=1, while a constant group has zero standard deviation. Define how to handle these cases before dividing.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
