Sub topic 1
Thinking in split-apply-combine
Prerequisites
This chapter assumes you can write basic Python functions and create a pandas DataFrame. It also assumes you can select columns and that you know what a Series and an index are. If any of these are unfamiliar, review them first.
The pattern
Many data questions have the same shape: "for each X, compute Y." What is the total revenue per region? What is the average order size per customer? Each question asks you to treat subsets of rows separately and then collect the answers.
Pandas models this with a three-step pattern called split-apply-combine:
- Split. Divide the rows into groups based on the values of one or more keys.
- Apply. Run a computation on each group independently. The computation might summarize the group, transform it, or filter it.
- Combine. Join the per-group results into a single Series or DataFrame.
A worked example
Here is a small sales table. The question is: what is the total revenue per region?
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
totals = df.groupby("region")["revenue"].sum()
print(totals)
# region
# North 175.0
# South 220.0
# Name: revenue, dtype: float64One line performs all three steps:
df.groupby("region")is the split. It records which rows belong to which region.["revenue"].sum()is the apply. It sums the revenue values inside each group.- The return value is the combine. It is a Series whose index holds the group keys,
NorthandSouth.
Without groupby, you would write the loop yourself: filter the rows for each region, sum them, and store the result in a dictionary or list. Groupby does this for you, and it runs faster than a Python loop.
What a GroupBy object really is
Calling df.groupby("region") does not compute anything yet. It returns a GroupBy object, which is a description of the split. The work happens when you call a method on it, such as sum().
g = df.groupby("region")
print(type(g))
# <class 'pandas.core.groupby.generic.DataFrameGroupBy'>
print(g.ngroups)
# 2This lazy design lets you reuse one GroupBy object for several computations. It also means that the choice of apply step controls the shape of your result.
Why the apply step matters
The apply step determines how the output relates to the input:
| Apply step | Output has one row per | Example use |
|---|---|---|
| Aggregation (`sum`, `mean`, `agg`) | group | Total revenue per region |
| `transform` | original row | Each row's share of its group total |
| `filter` | original row, but some groups dropped | Keep only large regions |
| `apply` | depends on your function | Custom logic |
Later chapters cover each of these in turn. For now, remember that the same split can lead to different output shapes. When a groupby result looks wrong, first check which apply step you used and what shape it produces.
Exercise
In the expression df.groupby("region")["revenue"].sum(), which part is the split, which is the apply, and which is the combine?
Show answer
df.groupby("region") is the split, because it divides the rows by region. The sum() call is the apply, because it computes a total for each group. The combine is the result that pandas returns, a Series indexed by region with one total per group.
Exercise
You want each row of df to carry its region's total revenue in a new column. Should the apply step be an aggregation or a transform, and why?
Show answer
A transform. An aggregation returns one row per group, but you need one value per original row, aligned to the original index. Transform returns that shape.