Chapter 4 used groupby to summarise. Its real power is in three lesser-known methods: transform (which keeps the original row count), filter (which drops entire groups), and apply (arbitrary per-group logic). These unlock analysis that's clumsy any other way.
Split–apply–combine, deeper
agg returns one row per group. But often you want each group's statistic attached back to every original row — that's what transform is for.
transform — keep the shape
transform returns a result the same length as the input, so you can add group-level stats as a new column — the key to "compare each row to its group":
# Each student's package vs their programme's averagedf["prog_avg"] = df.groupby("programme")["package"].transform("mean")df["vs_avg"] = df["package"] - df["prog_avg"]# Group-wise standardisation (z-score within each programme)df["z"] = df.groupby("programme")["package"].transform(lambda s: (s - s.mean()) / s.std())
filter — drop whole groups
filter keeps or discards entire groups based on a group-level condition:
# Keep only programmes with at least 10 studentsbig = df.groupby("programme").filter(lambda g: len(g) >= 10)# Keep groups whose average package clears a bardf.groupby("programme").filter(lambda g: g["package"].mean() > 7)
apply — custom per group
apply hands each group's sub-DataFrame to your function — use it for logic that isn't a simple aggregation, like "top 2 per group":
# Top 2 earners within each programmedf.groupby("programme").apply(lambda g: g.nlargest(2, "package")).reset_index(drop=True)
Practice
Add a column giving each row's value minus its group mean using transform. Use filter to keep only groups with enough rows. With apply, select the top 2 rows per group. Note which tasks needed which method.
Key takeaways
- 01agg collapses to one row per group; transform returns the original shape to add group stats per row.
- 02transform("mean") broadcasts a group statistic back onto every row — great for comparisons and z-scores.
- 03filter keeps or drops entire groups based on a group-level condition.
- 04apply passes each group's sub-DataFrame to a function for custom logic (e.g. top-n per group).
- 05Prefer agg/transform over apply for speed — apply is the flexible last resort.
