transform versus aggregate
One answer per group, or one answer per row.
aggregate collapses
A group of five rows becomes one. That is what you want for a summary table and not what you want for a new column.
import pandas as pd
df = pd.DataFrame({"k": ["a", "a", "b"], "v": [1, 3, 5]})
print(df.groupby("k")["v"].mean().to_dict())
transform keeps the shape
It gives every row its group's answer, so it lines up with the table and can be assigned straight back as a column.
import pandas as pd
df = pd.DataFrame({"k": ["a", "a", "b"], "v": [1, 3, 5]})
df["group_mean"] = df.groupby("k")["v"].transform("mean")
print(df["group_mean"].tolist())
Exercise
Try It YourselfWrite above_group_mean(df) returning the number of rows whose v is above the mean of their own group.
Press Run to see output