Skip to content
Codescope

Group-by: split, apply, combine

Three steps, one line of code. Knowing the three is what makes the line predictable.

core10 min7 steps

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
Rowregionthe keyamount
0north120
1south80
2north200
3east95
4north150
5south60

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.

01 / 07

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.

analysis.pyPython
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