Split-apply-combine: pandas' most powerful single idea.
works in three steps you don't have to write
yourself: split the data into groups by some key, apply a function to
each group, then combine the results back together. .agg/.apply
return one row per group (the data shrinks); .transform returns one row
per original row (same shape as the input, values broadcast per group).
import pandas aspd
df = pd.DataFrame({
"animal": ["cat", "cat", "dog", "dog"],
"age": [2.5, 3.0, 1.0, 5.0],
})
print(df.groupby("animal")["age"].mean()) # one row per groupprint(df.groupby("animal")["age"].transform("mean")) # one row per ORIGINAL row