Sub topic 8
Group-wise Calculations with groupby and transform
This chapter assumes you can build a DataFrame, select columns, and use column arithmetic and groupby at a basic level. The goal is to replace loops over groups, and loops that look up each row's group total, with one vectorised expression.
The loop you want to avoid
Suppose each row is a sale, and you want each sale's share of its store's total. A common first attempt computes the total for each store in a loop and then writes the result back row by row. That code runs Python-level work once per group and once per row.
groupby splits the rows by a key. An aggregation such as sum then returns one value per group. The shape of that result is the problem: you have one number per store, but you need one number per row.
Why transform fits
transform runs a calculation per group and returns a result with the same index as the original rows. Each group's value is repeated for every row in that group. Because the index matches, it lines up with the original column in an ordinary division.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b"],
"amount": [10, 30, 5, 15],
})
sales["share"] = sales["amount"] / sales.groupby("store")["amount"].transform("sum")
print(sales)The output is:
store amount share
0 a 10 0.25
1 a 30 0.75
2 b 5 0.25
3 b 15 0.75Store a totals 40, so its rows get 10/40 and 30/40. Store b totals 20, so its rows get 5/20 and 15/20.
agg versus transform
Both use the same groupby object. They differ in the shape they return.
| Method | Result shape | Typical use |
|---|---|---|
| `agg("sum")` | One row per group | Summary tables |
| `transform("sum")` | One row per original row | New column next to the data |
If you only need a summary, use agg. If you need the group value beside each row, use transform.
Other useful transforms
transform accepts the names of many built-in methods, such as "mean", "max", "min", "count" and "std". Built-in names run in optimised code. A custom Python function passed to transform is called once per group, so it is slower. Prefer a built-in name when one exists.
A common use is centring values within a group:
sales["centered"] = sales["amount"] - sales.groupby("store")["amount"].transform("mean")
print(sales[["store", "amount", "centered"]])Store a has a mean of 20 and store b has a mean of 10, so the centred values are -10, 10, -5 and 5.
Common errors
- Using
aggand then assigning the result to a column. The result has one row per group, so the indexes do not match and you getNaNvalues. - Grouping the whole frame and not selecting a column.
sales.groupby("store").transform("sum")tries to sum every non-key column, which can fail on text columns. Select the column first. - Passing a Python lambda to
transformwhen a built-in name would do. This works, but it runs per group in Python and loses most of the speed benefit.
Exercise
Given the sales DataFrame above, write one line that adds a column store_max holding the largest amount in each row's store.
Show answer
sales["store_max"] = sales.groupby("store")["amount"].transform("max")