Sub topic 1
Thinking in split-apply-combine
Most grouped analysis in pandas answers one question: what does this number look like for each category? Total revenue per region, average order size per customer, and the latest reading per sensor are all examples. The groupby method answers these questions with one idea, called split-apply-combine. This chapter builds that mental model and ties it to the GroupBy object. Later chapters cover the details of each method.
Prerequisites
This chapter assumes you can:
- Write basic Python, including functions, loops, and
lambdaexpressions. - Create a pandas
DataFrame, select columns, and filter rows with a boolean mask. - Read a
Seriesand understand that it carries an index of labels.
You do not need prior experience with groupby. The examples use pandas 2.x.
The three steps
Split-apply-combine is a pattern for computing something per group. It has three steps:
- Split. Divide the rows of a table into groups according to the values of one or more keys.
- Apply. Run an operation on each group independently. The operation might summarize the group, transform it, or test it.
- Combine. Collect the per-group results into one pandas object.
The pattern is older than pandas. Hadley Wickham described it in a paper on R data tools, and SQL's GROUP BY follows the same idea. In pandas, groupby performs the split. The apply and combine steps happen when you call a method such as sum, agg, transform, filter, or apply.
Doing it by hand first
The following code runs the three steps manually. It uses the sales table that the rest of this tutorial reuses.
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 = {}
for region in df["region"].unique(): # split: one pass per key
part = df[df["region"] == region] # the rows of one group
totals[region] = part["revenue"].sum() # apply: summarize the group
result = pd.Series(totals, name="revenue") # combine: build one Series
print(result)
# North 175.0
# South 220.0
# Name: revenue, dtype: float64This works, but it has problems. It rescans the whole table once per group. It handles only one key. It gives no control over ordering or missing keys. The loop also grows more complicated every time you add a requirement. groupby is the same computation with those details handled for you.
The same result with groupby
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: float64Read the expression from left to right:
df.groupby("region")splits the table by the values in theregioncolumn.["revenue"]selects the column to work on..sum()applies the sum to each group and combines the results.
The result is a Series whose index is the group keys. The index is named region, which the manual version did not do. Keeping the key name on the index is a small sign that pandas treats group keys as meaningful labels.
The GroupBy object is lazy
The call df.groupby("region") does not compute anything you can see. It returns a GroupBy object that records how the rows would be divided. The work happens when you call a method on it.
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],
})
g = df.groupby("region")
print(type(g).__name__)
# DataFrameGroupBy
print(g.ngroups)
# 2
print(g.size())
# region
# North 2
# South 3
# dtype: int64
for key, part in g:
print(key, len(part))
# North 2
# South 3Three facts about the object matter for the rest of the tutorial:
- It is reusable. You can store
gand call several methods on it, which avoids repeating the key definition. - Iterating over it yields
(key, sub-DataFrame)pairs. That is the split step made visible. Each sub-DataFrame keeps its original index labels. - Selecting a column with
g["revenue"]gives aSeriesGroupBy. Operations on it work on one column per group.
Four kinds of apply step
The apply step decides the shape of the result. Four GroupBy methods cover most needs, and the main skill in this tutorial is choosing the right one.
| Method | What each group produces | Shape of the combined result |
|---|---|---|
| `agg` (and `sum`, `mean`, and so on) | One value per group, per column | One row per group |
| `transform` | One value per original row | Same length and index as the input |
| `filter` | A True or False decision for the whole group | The original rows of the groups that passed |
| `apply` | Anything: a scalar, a Series, or a DataFrame | Depends on what the function returns |
The next block shows the three most common shapes side by side on the same data.
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],
})
by_region = df.groupby("region")
print(len(by_region["revenue"].sum()))
# 2 (aggregate: one row per group)
print(len(by_region["revenue"].transform("sum")))
# 5 (transform: one row per input row)
print(len(by_region.filter(lambda g: g["units"].sum() > 15)))
# 3 (filter: only the rows of South, whose units total 18)A quick rule for choosing:
- Use an aggregation when you want a summary table with one row per group.
- Use
transformwhen you need the group's value next to each original row, for example to compute a share or a z-score. - Use
filterwhen the question is "which groups qualify?" and you want their rows back. - Use
applyonly when none of the above fits. It is the most flexible and usually the slowest.
Edge cases to know now
Several behaviors surprise people at first. Later chapters treat each in detail, but you should recognize them early.
- Keys become the index. By default the group keys end up in the result's index, not in a column. Chapters on result shape cover
as_index=Falseandreset_index. - Keys are sorted. The default is
sort=True, so groups appear in sorted key order, not in order of first appearance. - Missing keys are dropped. Rows with
NaNin the key column are excluded from every group by default.dropna=Falsekeeps them as their own group. - Unselected columns come along. Calling
df.groupby("region").sum()without selecting a column applies the function to every non-key column. On a text column such asproduct,sumconcatenates strings, so North would show"AB". Select the columns you want first, as indf.groupby("region")[["units", "revenue"]].sum(). - A group always has at least one row. Groups are built from the rows that exist. A key value that never occurs creates no group, unless the key is categorical, which a later chapter covers.
A way to plan any groupby
Before writing code, answer three questions:
- What identifies a group? This gives the key or keys.
- What should happen inside each group? This gives the operation.
- What shape do I need back? This gives the method:
agg,transform,filter, orapply.
For example, "average revenue per region, as a table I can merge later" has the key region, the operation mean, and a one-row-per-group shape. That calls for an aggregation with as_index=False. "Each sale as a fraction of its region's revenue" has the same key but needs one value per input row, so it calls for transform.
Exercise
Using the sales table from this chapter, you want a new column that holds, for every row, the total units sold in that row's region. Which GroupBy method fits, and how many values does it return for this table?
Show answer
Use transform, for example df.groupby("region")["units"].transform("sum"). It returns one value per original row, so 5 values here: 15, 15, 18, 18, 18. An aggregation such as sum() would return only 2 values, one per region, which cannot be assigned directly as a column of the original table.
Exercise
What does df.groupby("region") compute at the moment it is called, and what makes the work happen?
Show answer
By itself it computes no results. It returns a lazy GroupBy object that records how the rows divide by region. The apply and combine steps run only when you call a method on it, such as sum(), agg(), transform(), filter(), apply(), or when you iterate over it.