Group-by: split, apply, combine
Three steps, one line of code. Knowing the three is what makes the line predictable.
Before you start
"Total sales per region", "average score per class", "count of orders per customer" — all of these follow the same pattern: split the rows into groups, apply a function to each group, combine the results.
Pandas gives you this with .groupby(). It looks like a single line of code, but three separate steps are happening: **split** (bucket rows by group key), **apply** (compute per bucket), **combine** (glue results back into one frame).
This lesson breaks that one line into its three phases so you can see exactly what happens between .groupby("region") and the final result.
df
6 rows| Row | regionthe key | amount |
|---|---|---|
| 0 | north | 120 |
| 1 | south | 80 |
| 2 | north | 200 |
| 3 | east | 95 |
| 4 | north | 150 |
| 5 | south | 60 |
6 rows, 3 distinct regions
The key column decides the piles. Everything else follows from that choice.
Step 1 of 7. Six rows, three regions. The question is "how much did each region sell?". Answering it by hand means sorting the rows into piles and adding up each pile. `groupby` is that process, named. Every group-by is three steps: **split** the rows by key, **apply** a function to each group, **combine** the answers.
Step 01 / 07
Six rows, three regions
The question is "how much did each region sell?". Answering it by hand means sorting the rows into piles and adding up each pile.
groupby is that process, named. Every group-by is three steps: **split** the rows by key, **apply** a function to each group, **combine** the answers.
import pandas as pddf = pd.read_csv("sales.csv")df.groupby("region")["amount"].sum()df.groupby("region").agg( total=("amount", "sum"), deals=("amount", "count"), best=("amount", "max"),)df.groupby("region", as_index=False)["amount"].sum()df.groupby("region")["amount"].transform("sum") # same shape as df