Sub topic 8
Aggregating across chunks: sums, counts and means
This chapter assumes you can read a CSV with read_csv, loop over a chunksize reader, and use groupby in pandas. You will compute totals, counts and means over a file that does not fit in memory.
The idea: reduce each chunk, then combine
You cannot call df["amount"].mean() on a file you never load in full. Instead, you keep a small running state. For each chunk you compute a partial result, and you merge it into the state. When the loop ends, the state holds the answer for the whole file.
This works for statistics that can be rebuilt from smaller pieces. Sums and counts combine by addition. Minimums and maximums combine by taking the min or max of the partial results. A mean is not directly combinable, but it equals the total sum divided by the total count, so you track those two values instead.
A single column: sum, count and mean
Start with one column. The running state is two numbers.
import pandas as pd
total = 0.0
count = 0
with pd.read_csv("sales.csv", usecols=["amount"], chunksize=200_000) as reader:
for chunk in reader:
total += chunk["amount"].sum()
count += chunk["amount"].count()
print("sum:", total)
print("count:", count)
print("mean:", total / count)count() counts non-missing values, which matches how mean() treats missing data. Using len(chunk) would count rows with missing amounts and give a wrong mean.
The memory use is one chunk at a time plus two numbers, regardless of file size.
Grouped aggregation
The same pattern works per group. Reduce each chunk with groupby, then add the partial tables together.
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)Three details matter here.
agg(["sum", "count"])returns a DataFrame indexed by region, with one column per statistic.add(..., fill_value=0)aligns the two tables on their index. A region that appears in only one of them is treated as 0 in the other, instead of becomingNaN.- The mean is computed once, after the loop. Averaging the per-chunk means would weight small chunks as heavily as large ones and give a wrong answer.
The running table has one row per distinct region, not one per input row. Memory stays small as long as the number of groups is small.
Other combinable statistics
| Statistic | Per-chunk result | How to combine |
|---|---|---|
| Sum | `sum` | Add |
| Count | `count` | Add |
| Mean | `sum` and `count` | Total sum / total count |
| Min / max | `min` / `max` | `min` / `max` of partials |
| Variance | `sum`, sum of squares, `count` | Compute from the three totals |
Variance and standard deviation are possible, but you must carry the sum of squares as well. Medians and exact percentiles are not combinable this way, because they depend on the full ordering of the data.
Verify against a small file
Before running on the real file, check your chunked result against a direct computation on a sample small enough to load. Use a tiny chunksize so that several chunks are processed.
import pandas as pd
df = pd.read_csv("sales.csv", nrows=1_000)
expected = df.groupby("region")["amount"].mean()
df.to_csv("sample.csv", index=False)
totals = None
with pd.read_csv("sample.csv", usecols=["region", "amount"], chunksize=100) 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)
actual = totals["sum"] / totals["count"]
print(((actual - expected).abs() < 1e-9).all())If this prints True, the combining logic is sound.
Exercises
Exercise
A file is read in chunks of 100,000 rows. Chunk 1 has sum 500 and count 100,000. Chunk 2 has sum 30 and count 10. What is the overall mean, and why is the average of the two chunk means wrong?
Show answer
The overall mean is (500 + 30) / (100,000 + 10) = 530 / 100,010, about 0.0053. The chunk means are 0.005 and 3.0. Their average, 1.5025, treats the 10-row chunk as equal in weight to the 100,000-row chunk, so it is far off.
Exercise
In the grouped example, what would go wrong if you used totals.add(part) without fill_value=0, and a region appeared only in the second chunk?
Show answer
Pandas aligns the tables on the index. For a region present in only one table, the other side is missing, so the sum and count for that region become NaN. The region's data from the first chunk where it appeared would be lost. With fill_value=0, the missing side counts as 0 and the values are kept.