Sub topic 1
Thinking in split-apply-combine
groupby follows the split-apply-combine pattern:
- Split rows into groups using one or more keys.
- Apply a calculation to each group.
- Combine the results into a Series or DataFrame.
A GroupBy object stores the grouping instructions. It does not calculate a result until you select an operation such as sum() or mean().
Prerequisites
This chapter assumes basic Python functions, pandas DataFrames, column selection, Series, and the pandas index.
Your first groupby
Suppose each row records a product sale. To calculate revenue by region, group by region and select the revenue column:
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)The result contains one value per region: North has 175.0, and South has 220.0. The grouping column becomes the result's index.
Choosing grouping keys
A grouping key can be:
- One column, such as
"region". - Several columns, such as
["region", "product"]. - An index level, using
level=. - A Series or computed key aligned with the DataFrame rows.
Grouping by several columns creates one group for each combination:
by_region_product = (
df.groupby(["region", "product"], as_index=False)["revenue"].sum()
)
print(by_region_product)as_index=False keeps region and product as ordinary columns. Without it, pandas uses those keys as a MultiIndex.
Aggregating with built-in functions
Common built-in aggregations include sum, mean, min, max, first, and nunique. Select an appropriate function for the question you are answering.
| Question | Aggregation |
|---|---|
| Total revenue? | `sum` |
| Average revenue? | `mean` |
| Number of distinct products? | `nunique` |
Use agg when one grouping needs several summaries:
summary = df.groupby("region").agg(
total_units=("units", "sum"),
average_revenue=("revenue", "mean"),
product_count=("product", "nunique"),
)
print(summary)Named aggregation gives readable output columns and avoids a complicated multi-level column index.
Exercise
Which expression calculates total revenue for each region and product combination?
Show answer
df.groupby(["region", "product"])["revenue"].sum()