Sub topic 9
Combining grouped results from many chunks
This chapter assumes you can read a CSV with chunksize, you know groupby and agg, and you have seen how a total or count is built up chunk by chunk. Here the same idea is applied per group. Each chunk produces a small table of partial results, and you merge those tables as you go.
The working model
A grouped result for one chunk is a table indexed by the group key. Different chunks contain different keys. One chunk may have no rows for "north", and another may have a key that no earlier chunk had. So you cannot simply stack the tables or add them by position. You need to align them by key and combine the values.
The pattern has three steps:
- Reduce each chunk to a small table of combinable values, such as a sum and a count per group.
- Merge that table into a running total, aligning rows by group key.
- After the last chunk, compute any derived value, such as the mean, from the combined totals.
A complete example
This script reads sales.csv and computes the mean amount per region. It loads only the two columns it needs.
import pandas as pd
totals = None
with pd.read_csv("sales.csv", usecols=["region", "amount"], chunksize=200_000) as reader:
for chunk in reader:
part = chunk.groupby("region")["amount"].agg(["sum", "count"])
totals = part if totals is None else totals.add(part, fill_value=0)
totals["mean"] = totals["sum"] / totals["count"]
print(totals)The key line is totals.add(part, fill_value=0). The add method aligns the two tables on their index. Where a key exists in only one table, fill_value=0 treats the missing side as zero. Without it, that key would become NaN and the earlier total would be lost.
The first chunk has nothing to add to, so the code starts with totals = None and assigns the first partial result directly.
Why you keep sums and counts
The mean of each chunk's means is not the overall mean unless every chunk has the same number of rows for that group. The script avoids this by keeping the sum and count, which can be added exactly. The division happens once, at the end.
| Statistic | Keep per chunk | Combine with | Final step |
|---|---|---|---|
| Sum | sum | add | none |
| Count | count | add | none |
| Mean | sum and count | add both | sum / count |
| Minimum | min | element-wise minimum | none |
| Maximum | max | element-wise maximum | none |
For min and max, add is the wrong operation. You can concatenate the partial tables and group again:
import pandas as pd
extremes = None
with pd.read_csv("sales.csv", usecols=["region", "amount"], chunksize=200_000) as reader:
for chunk in reader:
part = chunk.groupby("region")["amount"].agg(["min", "max"])
if extremes is None:
extremes = part
else:
combined = pd.concat([extremes, part])
extremes = combined.groupby(level=0).agg({"min": "min", "max": "max"})
print(extremes)Concatenating and regrouping by the index (level=0) works for any statistic that can be combined this way. The running table stays small because it has one row per group, not one row per input row.
Multiple group keys
Grouping by several columns produces a MultiIndex. The add method aligns on all levels, so the pattern is unchanged. Pass a list to groupby, such as ["region", "product"]. The memory you need depends on the number of distinct key combinations, not on the file size.
Common errors
- Forgetting
fill_value=0. Groups missing from one side becomeNaN, and your totals are silently wrong. - Averaging chunk means. This gives a biased result when group sizes differ between chunks.
- Too many groups. If the key has millions of distinct values, the running table is itself large. Check with
memory_usage(deep=True)or consider a different tool. - Category dtype surprises. If the key column is a
category,groupbymay include unobserved categories. Passobserved=Trueto keep the partial tables small.
Exercise
A file has columns store and price. You group each chunk by store and compute the mean price, then average the chunk means for each store. Why can this give a wrong answer, and what should you store per chunk instead?
Show answer
Chunks can contain different numbers of rows for a store, so the average of chunk means weights each chunk equally instead of each row. Store the sum and the count of price per store in each chunk, add them across chunks with add(..., fill_value=0), and divide the total sum by the total count at the end.
Exercise
What happens to a group that appears in the running table but not in the current chunk if you call totals.add(part) without fill_value?
Show answer
The result for that group becomes NaN, because the missing side is treated as missing rather than zero. Use fill_value=0 so the existing total is kept.