Skip to main content
Albero Academy

Advanced GroupBy

Go beyond simple aggregation — transform to broadcast group stats back, filter whole groups, and apply custom per-group logic.

Chapter 10Pandas16 min readBeginner friendly
  • #Pandas
  • #GroupBy
  • #Transform

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":

group stat on every row
# Each student's package vs their programme's average
df["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 substantial groups
# Keep only programmes with at least 10 students
big = df.groupby("programme").filter(lambda g: len(g) >= 10)
# Keep groups whose average package clears a bar
df.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":

arbitrary group logic
# Top 2 earners within each programme
df.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

  1. 01agg collapses to one row per group; transform returns the original shape to add group stats per row.
  2. 02transform("mean") broadcasts a group statistic back onto every row — great for comparisons and z-scores.
  3. 03filter keeps or drops entire groups based on a group-level condition.
  4. 04apply passes each group's sub-DataFrame to a function for custom logic (e.g. top-n per group).
  5. 05Prefer agg/transform over apply for speed — apply is the flexible last resort.