Sub topic 8
Aggregating across chunks: sums, counts and means
This chapter assumes you can write a Python for loop and a with block, that you know pandas DataFrames and read_csv, and that you have used groupby with agg. It also assumes you already know how to read a CSV in chunks with chunksize. Here the question is how to compute a statistic when no single DataFrame ever holds all the rows.
The core idea: reduce each chunk, then combine
A chunked loop sees one slice of the data at a time. To get a result for the whole file, each chunk is reduced to a small partial result. The partial results are then merged. The merged result is turned into the final answer.
This works when the statistic can be built from pieces that add together. A total is the sum of the chunk totals. A row count is the sum of the chunk counts. A mean is not the mean of the chunk means, but it is the total sum divided by the total count. So you carry the sum and the count, and you divide only once, at the end.
Memory use stays small because only one chunk and one running result exist at any moment. The running result is the size of the answer, not the size of the input.
A single running total
Start with the simplest case, a column total and a row count. The file is read with only the needed column, which also reduces memory.
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 if count else float("nan"))Two details matter here.
Series.sum()skips missing values by default, andSeries.count()counts only non-missing values. Because both ignoreNaN, the final mean matches whatdf["amount"].mean()would give on the whole file.len(chunk)counts all rows, including rows whereamountis missing. If you usedlen(chunk)as the denominator, the mean would be too low whenever the column has gaps. Usecount()for the denominator of a mean, andlen()only when you want a row count.
The guard if count else float("nan") avoids a ZeroDivisionError when the file has no valid values.
Several columns at once
You can carry the same pair of numbers for many columns. A small dictionary or a Series keeps the code tidy.
import pandas as pd
cols = ["amount", "quantity", "discount"]
sums = pd.Series(0.0, index=cols)
counts = pd.Series(0, index=cols)
with pd.read_csv("sales.csv", usecols=cols, chunksize=200_000) as reader:
for chunk in reader:
sums += chunk.sum()
counts += chunk.count()
means = sums / counts
print(pd.DataFrame({"sum": sums, "count": counts, "mean": means}))chunk.sum() returns one value per column, indexed by column name. Adding two Series aligns them on the index, so each column's total is added to the matching running total.
Minimum, maximum and other combinable statistics
A statistic is combinable if you can merge two partial results into the result for the combined data. The table lists common ones.
| Statistic | What each chunk keeps | How partials combine |
|---|---|---|
| Sum | chunk sum | add |
| Row count | chunk count | add |
| Mean | chunk sum and chunk count | add both, then divide |
| Minimum | chunk minimum | minimum of the minimums |
| Maximum | chunk maximum | maximum of the maximums |
| Variance, standard deviation | count, sum, sum of squares | add all three, then compute |
| Distinct values (small set) | set of values | union of sets |
A running minimum and maximum look like this:
import pandas as pd
lo = float("inf")
hi = float("-inf")
with pd.read_csv("sales.csv", usecols=["amount"], chunksize=200_000) as reader:
for chunk in reader:
if chunk["amount"].notna().any():
lo = min(lo, chunk["amount"].min())
hi = max(hi, chunk["amount"].max())
print(lo, hi)The notna().any() check handles a chunk where every value is missing. In that case min() returns NaN, and min(lo, nan) gives an order-dependent result because comparisons with NaN are always false.
Variance from sums of squares
For variance you carry three numbers: the count n, the sum s, and the sum of squares q. The population variance is q / n - (s / n) ** 2.
import pandas as pd
n = 0
s = 0.0
q = 0.0
with pd.read_csv("sales.csv", usecols=["amount"], chunksize=200_000) as reader:
for chunk in reader:
values = chunk["amount"].dropna()
n += len(values)
s += values.sum()
q += (values ** 2).sum()
mean = s / n
variance = q / n - mean ** 2
print("variance:", variance)
print("std:", variance ** 0.5)This formula can lose precision when the mean is large compared with the spread, because it subtracts two nearly equal large numbers. For data like timestamps in seconds or large IDs, subtract a constant (for example the first value seen) from every value before squaring, or use a numerically stable merge such as Welford's or Chan's algorithm. For ordinary business amounts the simple version is usually fine.
Counting categories
Counting how often each value appears is another combinable task. Each chunk gives a value_counts(), and counts add by label.
import pandas as pd
counts = pd.Series(dtype="int64")
with pd.read_csv("events.csv", usecols=["status"], chunksize=200_000) as reader:
for chunk in reader:
counts = counts.add(chunk["status"].value_counts(), fill_value=0)
print(counts.astype("int64").sort_values(ascending=False))add(..., fill_value=0) matters. Without it, a label that appears in only one of the two Series becomes NaN. With it, the missing side counts as zero. The result becomes a float Series, so the final astype("int64") restores integers.
This approach keeps one entry per distinct value. If the column has millions of distinct values, the running result is large, and you have moved the memory problem rather than removed it.
Grouped sums, counts and means
Grouped aggregation uses the same pattern. Each chunk is grouped, and the group-level partials are added together by group key. The next chapter covers this in more depth. The basic form is:
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 mean column is computed after the loop, from the combined sum and count. It is never added across chunks.
Common errors
- Averaging the chunk means.
mean(mean_1, mean_2, ...)weights every chunk equally. If the last chunk has 10 rows and the others have 200,000, the result is wrong. Carry sums and counts. - Dividing by
len(chunk). This includes rows with missing values. Usecount()when the mean should ignore them. - Forgetting the last chunk. The last chunk is usually smaller than
chunksize. Code that assumes a fixed size, such asn_chunks * chunksize, overcounts. Always add the reallenorcount. - Starting a running total with the first chunk's type. Mixing an integer accumulator with float results is harmless. Starting
totalsasNoneand handling the first chunk as a special case, as above, avoids shape mismatches. - Skipping
fill_value. Adding grouped partials with+instead ofadd(..., fill_value=0)turns groups that are absent from one chunk intoNaN. - Integer overflow. If a column is read as a small integer dtype such as
int8,chunk.sum()on NumPy may still widen the result, but arithmetic you do yourself, such as squaring, can overflow. Convert with.astype("float64")before squaring.
A sanity check on a sample
Before you trust a chunked result on a 50 GB file, test the logic on a file small enough to load whole. Compare the chunked answer with the plain pandas answer, using a tiny chunksize so that many chunks are produced.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({"amount": rng.normal(100, 15, 1_000)})
df.loc[::7, "amount"] = np.nan
df.to_csv("check.csv", index=False)
total, count = 0.0, 0
with pd.read_csv("check.csv", chunksize=64) as reader:
for chunk in reader:
total += chunk["amount"].sum()
count += chunk["amount"].count()
print(np.isclose(total / count, df["amount"].mean()))The script prints True. The chunk size of 64 does not divide 1,000, so the last chunk is short, and the missing values test the count() logic. A wrong implementation, such as dividing by len(chunk), would print False.
Exercise
A file has an amount column with some missing values. A colleague computes the mean by taking chunk["amount"].mean() for each chunk and averaging those numbers. Give two separate reasons this can differ from df["amount"].mean() on the full data, and say what to carry between chunks instead.
Show answer
First, chunks with different numbers of valid values should carry different weight, but averaging the chunk means gives each chunk the same weight, which matters most for the short last chunk. Second, a chunk whose values are all missing has a mean of NaN, which can poison the average or be handled inconsistently. Carry the running sum (chunk["amount"].sum()) and the running count of non-missing values (chunk["amount"].count()), then compute total_sum / total_count once after the loop.
Exercise
Write the per-chunk code that keeps what you need to compute the population standard deviation of a column x across all chunks, ignoring missing values. Then give the final formula.
Show answer
Keep three accumulators: n, s and q. In each chunk, set v = chunk["x"].dropna().astype("float64"), then n += len(v), s += v.sum(), q += (v ** 2).sum(). After the loop, mean = s / n, variance = q / n - mean ** 2, and the standard deviation is variance ** 0.5.