GroupBy and Aggregation
"What is the total per region?", "What's the average per month?", "How many orders per customer?" All of these follow one pattern called split–apply–combine:
- Split the rows into groups by the values of one or more columns.
- Apply a calculation (sum, mean, count…) to each group.
- Combine the results into a new table.
In pandas, the whole pattern is one line with groupby().
A first groupby
Our data: a few days of sales from a chain of three food trucks.
import pandas as pd
sales = pd.DataFrame({
"truck": ["Taco", "Wok", "Taco", "Crepe", "Wok", "Taco", "Crepe", "Wok"],
"day": ["Fri", "Fri", "Sat", "Sat", "Sat", "Sun", "Sun", "Sun"],
"orders": [84, 61, 120, 45, 98, 101, 52, 77],
"revenue": [756.0, 610.0, 1104.0, 382.5, 1029.0, 919.1, 457.6, 785.4],
})
print(sales.groupby("truck")["revenue"].sum())
print(sales.groupby("truck")[["orders", "revenue"]].mean().round(1))truck
Crepe 840.1
Taco 2779.1
Wok 2424.4
Name: revenue, dtype: float64
orders revenue
truck
Crepe 48.5 420.0
Taco 101.7 926.4
Wok 78.7 808.1
The group keys (the truck names) become the index of the result, sorted alphabetically. Selecting a column after groupby (["revenue"]) limits the calculation to it.
Common aggregations
| Method | Per group |
|---|---|
sum(), mean(), median() |
total, average, middle value |
min(), max() |
extremes |
count() |
non-missing values |
size() |
number of rows (including missing) |
nunique() |
distinct values |
first(), last() |
first/last row's value |
std(), var() |
spread |
import pandas as pd
sales = pd.DataFrame({
"truck": ["Taco", "Wok", "Taco", "Crepe", "Wok", "Taco", "Crepe", "Wok"],
"day": ["Fri", "Fri", "Sat", "Sat", "Sat", "Sun", "Sun", "Sun"],
"orders": [84, 61, 120, 45, 98, 101, 52, 77],
})
print(sales.groupby("day").size())
print(sales.groupby("day")["orders"].max())
print(sales.groupby("truck")["day"].nunique())day
Fri 2
Sat 3
Sun 3
dtype: int64
day
Fri 84
Sat 120
Sun 101
Name: orders, dtype: int64
truck
Crepe 2
Taco 3
Wok 3
Name: day, dtype: int64
Several aggregations with agg()
agg() takes a list of functions, or a dictionary choosing functions per column:
import pandas as pd
sales = pd.DataFrame({
"truck": ["Taco", "Wok", "Taco", "Crepe", "Wok", "Taco", "Crepe", "Wok"],
"orders": [84, 61, 120, 45, 98, 101, 52, 77],
"revenue": [756.0, 610.0, 1104.0, 382.5, 1029.0, 919.1, 457.6, 785.4],
})
print(sales.groupby("truck")["revenue"].agg(["sum", "mean", "max"]).round(1))
print(sales.groupby("truck").agg({"orders": "sum", "revenue": ["mean", "max"]}).round(1)) sum mean max
truck
Crepe 840.1 420.0 457.6
Taco 2779.1 926.4 1104.0
Wok 2424.4 808.1 1029.0
orders revenue
sum mean max
truck
Crepe 97 420.0 457.6
Taco 305 926.4 1104.0
Wok 236 808.1 1029.0
Named aggregation
The dictionary form creates two-level column names, which are awkward to work with. Named aggregation gives you flat, self-chosen names: new_name=("column", "function").
import pandas as pd
sales = pd.DataFrame({
"truck": ["Taco", "Wok", "Taco", "Crepe", "Wok", "Taco", "Crepe", "Wok"],
"orders": [84, 61, 120, 45, 98, 101, 52, 77],
"revenue": [756.0, 610.0, 1104.0, 382.5, 1029.0, 919.1, 457.6, 785.4],
})
summary = sales.groupby("truck").agg(
days=("orders", "size"),
total_orders=("orders", "sum"),
total_revenue=("revenue", "sum"),
best_day=("revenue", "max"),
)
summary["avg_ticket"] = (summary["total_revenue"] / summary["total_orders"]).round(2)
print(summary.sort_values("total_revenue", ascending=False)) days total_orders total_revenue best_day avg_ticket
truck
Taco 3 305 2779.1 1104.0 9.11
Wok 3 236 2424.4 1029.0 10.27
Crepe 2 97 840.1 457.6 8.66
This is the form most professionals use for reports.
Grouping by several columns
Pass a list of columns. The result has a MultiIndex (one level per key); reset_index() turns it back into ordinary columns, and as_index=False does that directly:
import pandas as pd
shifts = pd.DataFrame({
"store": ["North", "North", "North", "South", "South", "South"],
"role": ["barista", "barista", "cashier", "barista", "cashier", "cashier"],
"hours": [6, 8, 7, 5, 8, 4],
})
print(shifts.groupby(["store", "role"])["hours"].sum())
print(shifts.groupby(["store", "role"], as_index=False)["hours"].sum())store role
North barista 14
cashier 7
South barista 5
cashier 12
Name: hours, dtype: int64
store role hours
0 North barista 14
1 North cashier 7
2 South barista 5
3 South cashier 12
Looping over groups
You can iterate over a groupby to see each group as its own small DataFrame, which helps when learning or debugging:
import pandas as pd
shifts = pd.DataFrame({
"store": ["North", "North", "South", "South", "South"],
"hours": [6, 8, 5, 8, 4],
})
for store, group in shifts.groupby("store"):
print(f"{store}: {len(group)} shifts, {group['hours'].sum()} hours")
print(shifts.groupby("store").get_group("South"))North: 2 shifts, 14 hours
South: 3 shifts, 17 hours
store hours
2 South 5
3 South 8
4 South 4
Tip: Missing values in a key column are dropped from the groups by default. Pass
dropna=Falseto keep them as their own group.
Test yourself
What becomes the index of df.groupby("city")["sales"].sum()?
- 0, 1, 2…
- The city values
- The sales values
- Nothing
What is the difference between size() and count() on a group?
- None
- size counts all rows; count counts non-missing values
- count counts all rows; size counts non-missing values
- size returns bytes
Which creates a column named total holding the sum of amount per group?
- g.agg(total=("amount", "sum"))
- g.agg("amount" = sum)
- g.sum(name="total")
- g.total("amount")