Sub topic 8
Group-wise calculations with groupby and transform
Many row loops exist to answer a question about a group: what share of its store's sales is this row, how far is this reading from its sensor's average, which rows belong to groups that pass a test. This chapter replaces those loops with groupby and transform. It assumes you can index a DataFrame, you know the vectorised arithmetic and boolean masks from earlier chapters, and you know that a Series aligns on its index.
The loop you are replacing
Take a small sales table. You want each row's amount as a share of its store's total.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b"],
"amount": [10, 30, 5, 15],
})
sales["share_loop"] = 0.0
for store in sales["store"].unique():
mask = sales["store"] == store
total = sales.loc[mask, "amount"].sum()
sales.loc[mask, "share_loop"] = sales.loc[mask, "amount"] / total
print(sales)This is not a row loop, but it is still a loop over groups. Each pass builds a boolean mask over the whole frame, filters it twice, and assigns back with .loc. The cost grows with the number of groups times the number of rows. With 500 stores and 100,000 rows, the code scans the 100,000-row store column 500 times.
The split-apply-combine model
groupby splits the rows by key, applies an operation to each piece, and combines the results. The three methods you will use differ in what they return.
| Method | Result shape | Typical use |
|---|---|---|
| `agg` (or `.sum()`, `.mean()`) | One row per group | A summary table |
| `transform` | Same length and index as the input | A new column aligned with the original rows |
| `apply` | Depends on the function | Logic that needs the whole group as a DataFrame |
Group totals without a loop
transform("sum") computes the sum for each group and repeats it on every row of that group, in the original row order.
sales["store_total"] = sales.groupby("store")["amount"].transform("sum")
sales["share"] = sales["amount"] / sales["store_total"]
print(sales[["store", "amount", "store_total", "share"]])The output is:
store amount store_total share
0 a 10 40 0.25
1 a 30 40 0.75
2 b 5 20 0.25
3 b 15 20 0.75You can write the same thing in one line:
sales["share"] = sales["amount"] / sales.groupby("store")["amount"].transform("sum")Because transform returns a Series with the same index as sales, the division lines up row for row. This is the index alignment from the previous chapter doing the work.
Why not agg and then merge?
You can get the same result in two steps. Aggregate to one row per group, then look the totals up for each row.
totals = sales.groupby("store")["amount"].sum()
sales["share_map"] = sales["amount"] / sales["store"].map(totals)This is also vectorised and works well. The choice is mostly about readability. Use transform when the group statistic is only a means to an end, and keep the summary table when you also need it for something else, such as a report. Doing both from one agg call avoids computing the groups twice.
Common group statistics with transform
Pass the name of a built-in reduction as a string. These names run on optimised code paths.
g = sales.groupby("store")["amount"]
sales["store_mean"] = g.transform("mean")
sales["store_max"] = g.transform("max")
sales["store_rows"] = g.transform("count")
sales["z"] = (sales["amount"] - g.transform("mean")) / g.transform("std")
sales["rank_in_store"] = g.rank(ascending=False)Notes on these lines:
- Saving
gonce avoids repeating the grouping expression. The groups are still computed lazily when each method runs. stdusesddof=1by default, as in pandas generally, so a group with one row givesNaNforz.rankis not a reduction. It returns one value per row, so you call it directly on the grouped object. It returns floats because ties are averaged by default.countignores missing values. Use"size"on a DataFrameGroupBy to count rows including missing values.
Filling gaps with a group statistic
A common loop fills each missing value with the mean of its group. Since fillna accepts a Series and aligns it on the index, you can pass the transformed means directly.
import numpy as np
readings = pd.DataFrame({
"sensor": ["x", "x", "y", "y"],
"value": [1.0, np.nan, 4.0, 6.0],
})
group_mean = readings.groupby("sensor")["value"].transform("mean")
readings["filled"] = readings["value"].fillna(group_mean)
print(readings)The NaN in sensor x is replaced by 1.0, the mean of that sensor's only non-missing value. The mean skips missing values by default, so the gap does not poison the group statistic.
Filtering rows by a group property
Another loop pattern keeps only the rows that belong to groups meeting a condition. Combine transform with a boolean mask.
big_stores = sales[sales.groupby("store")["amount"].transform("max") > 20]
print(big_stores[["store", "amount"]])The mask is a boolean Series aligned with sales. Every row of store a passes, because that store's maximum is 30. Store b has a maximum of 15, so none of its rows pass. The same idea works for "groups with at least three rows" using transform("count") >= 3.
If you only need whole groups kept or dropped, groupby(...).filter(func) does the same. It calls a Python function once per group, so the mask form is usually faster on many groups.
Measuring it
Check equivalence before comparing speed, as in the earlier measuring chapter. This script builds 100,000 rows in 500 groups.
import timeit
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
big = pd.DataFrame({
"store": rng.integers(0, 500, 100_000),
"amount": rng.integers(1, 100, 100_000),
})
def share_loop(frame):
out = pd.Series(0.0, index=frame.index)
for key in frame["store"].unique():
mask = frame["store"] == key
part = frame.loc[mask, "amount"]
out[mask] = part / part.sum()
return out
def share_transform(frame):
return frame["amount"] / frame.groupby("store")["amount"].transform("sum")
pd.testing.assert_series_equal(
share_loop(big), share_transform(big), check_names=False
)
print("loop :", timeit.timeit(lambda: share_loop(big), number=3))
print("transform:", timeit.timeit(lambda: share_transform(big), number=3))The exact numbers depend on your machine. The loop's time grows with the number of groups, because each group triggers a full-column comparison. The transform version makes one pass to find the groups and one to reduce them, so it should be much faster, and the gap widens as the number of groups increases.
Custom functions and their cost
transform also accepts a function or lambda. It is called once per group, receiving the group's Series.
sales["centered"] = sales.groupby("store")["amount"].transform(lambda s: s - s.mean())This is correct, but it runs Python code once per group, so with thousands of groups you pay the loop cost again. Prefer the vectorised equivalent that uses built-in reductions:
sales["centered"] = sales["amount"] - sales.groupby("store")["amount"].transform("mean")Use a lambda inside transform only when no combination of built-in methods expresses the logic. Try transform("mean"), arithmetic, rank, cumsum and shift first.
Edge cases and common errors
- Missing keys. By default
groupbydrops rows whose key isNaN. Intransform, those rows receiveNaNin the result. Passdropna=Falseif they should form their own group. - Row order and sorting.
transformreturns values in the original row order and index, even if the keys are unsorted. Thesortargument only affects the order ofaggoutput. - Wrong shape. A function passed to
transformmust return a result with the same length as the group, or a single value that can be broadcast. Returning a shorter Series raises an error. - Duplicate index labels. Assigning a transformed Series to another frame aligns on labels. If the target has duplicates or a different index, you get
NaNvalues or an error. Assign within the same frame or callreset_index(drop=True)on both. - Selecting the column first.
sales.groupby("store")["amount"].transform("sum")returns a Series. Callingtransformon the whole grouped frame returns a DataFrame of all non-key columns, which may include columns you did not intend to reduce. - Multiple keys.
groupby(["store", "day"])groups by the combination. The same code works with no further changes. - Categorical keys. If the key column is categorical,
groupbymay include unused categories inaggoutput. Check theobservedargument for your pandas version.
What comes next
transform("sum") repeats one value across a group. The next chapter covers previous-row and running-total logic, where each row gets its own value computed from the rows before it. That uses the same groupby object with diff, shift and cumsum.
Exercise
A DataFrame orders has columns customer and value. Write one line that adds a column vs_avg containing each order's value divided by the average order value of that same customer, with no loop and no lambda.
Show answer
orders["vs_avg"] = orders["value"] / orders.groupby("customer")["value"].transform("mean")
Exercise
Using the sales frame from this chapter, you want to keep only rows from stores that have at least three rows. Why is sales.groupby("store")["amount"].count() >= 3 the wrong mask, and what should you use instead?
Show answer
The count() call aggregates, so it returns one value per store with the store names as its index. That does not line up with the row labels of sales, so it cannot select rows correctly. Use transform("count"), which returns one value per original row: sales[sales.groupby("store")["amount"].transform("count") >= 3].