Where a groupby().agg() call reduces each group down to one summary row, groupby().transform() instead broadcasts the computed result back out to match the original DataFrame's full shape and row count — every row in a group gets that group's computed value, like the group's mean, attached right alongside its own original value. This makes transform() the right tool for tasks like computing each row's deviation from its group's average, since it produces a result aligned row-for-row with the original data, ready to subtract or compare directly.
1Understanding df.transform()
Where a groupby().agg() call reduces each group down to one summary row, groupby().transform() instead broadcasts the computed result back out to match the original DataFrame's full shape and row count — every row in a group gets that group's computed value, like the group's mean, attached right alongside its own original value. This makes transform() the right tool for tasks like computing each row's deviation from its group's average, since it produces a result aligned row-for-row with the original data, ready to subtract or compare directly.
Use groupby().transform() specifically when you need each row to keep its own individual value while also gaining a group-level computed value alongside it, like normalizing each value against its group's mean — agg() alone can't do this, since it collapses each group down to one row and loses that per-row alignment.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
df["team_avg"] = df.groupby("team")["score"].transform("mean")
print(df)2Practical Example
Here is a real-world application of df.transform() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
df["deviation"] = df["score"] - df.groupby("team")["score"].transform("mean")
print(df)3Best Practices
Follow these guidelines when working with df.transform():
1. Use transform() when the result needs to align row-for-row with the original DataFrame, unlike agg()'s group-collapsing behavior
2. Use transform() to compute group-relative values, like each row's deviation from its group's mean, in a way ready for direct subtraction from the original column
3. Use agg() instead when you actually want one summary row per group, not a value repeated across every row in that group
Tip: Use groupby().transform() specifically when you need each row to keep its own individual value while also gaining a group-level computed value alongside it, like normalizing each value against its group's mean — agg() alone can't do this, since it collapses each group down to one row and loses that per-row alignment.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
df["team_avg"] = df.groupby("team")["score"].transform("mean")
print(df)