pandas groupby
Every "give me sum/mean/count by X" analysis in the world is a groupby.
The three phases
- Split: rows into buckets by one or more columns.
- Apply: run a function on each bucket.
- Combine: stitch the results back together.
The three apply modes
Aggregate — reduces each group to a scalar
df.groupby("region").revenue.sum()
df.groupby(["region","product"]).agg(total_qty=("quantity","sum"))
Named aggregations (2nd form) are the modern, readable way.
Transform — returns same shape as input
df["z_score"] = df.groupby("region").revenue.transform(
lambda s: (s - s.mean()) / s.std()
)
Use when you want a per-row value normalized within each group — running totals, group means broadcast back, percent-of-total.
Filter — keeps or drops entire groups
df.groupby("region").filter(lambda g: g.revenue.sum() > 500)
Common patterns
- Top-N per group:
df.sort_values("revenue", ascending=False).groupby("region").head(3) - Pivot table:
df.pivot_table(index="region", columns="product", values="revenue", aggfunc="sum") - Rolling within group:
df.groupby("id").value.rolling(7).mean()— 7-day rolling mean per user.
Performance
- Prefer builtin ops (
.sum(),.mean()) over.apply(lambda x: ...)— 5–50× faster. - Sort by group cols first if grouping is a bottleneck.
Try it
- Compute average quantity per (region, product).
- Rank products by revenue within each region.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Given the sales DataFrame below, group by
regionand print the total quantity per region as a Series. Expected values: North=15, South=20. - Exercise 2
Using the same sales frame with an added
pricecolumn[50, 30, 55, 28, 48], group by region and use named aggregations to compute total_qty (sum of quantity) and avg_price (mean of price). Store inagg. - Exercise 3
Add a new column
pct_of_region= each row's quantity as a fraction of its region's total quantity. Use.groupby(...).transform("sum")to broadcast the group totals back. The North total is 15 → row with qty=5 should show pct 5/15 ≈ 0.333.