Sub topic 11
Pitfalls: non-combinable statistics, dtype drift and accidental full loads
This chapter assumes you can write a chunked loop with read_csv(..., chunksize=...) and combine partial groupby results. Chunked code often runs without errors and still gives wrong numbers, or runs out of memory anyway. Three causes account for most of these failures.
Pitfall 1: statistics that cannot be combined
A statistic is combinable if you can compute it from small per-chunk summaries. Sums, counts, minimums and maximums are combinable. A mean is combinable if you keep the sum and the count. Averaging the per-chunk means is wrong when chunks have different sizes or different numbers of missing values.
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(total / count)count() skips missing values, which matches how mean() behaves.
Medians, percentiles, modes and distinct counts are not combinable. The median of per-chunk medians is not the overall median, and no small summary fixes that. Your options are:
- For distinct counts, keep a set of seen values. This works while the number of distinct values fits in memory.
- For approximate quantiles, use a sketch library, or accept an estimate.
- For exact medians, use a tool that sorts or partitions out of core (see the last chapter).
import pandas as pd
seen = set()
with pd.read_csv(
"events.csv", usecols=["user_id"], dtype={"user_id": "string"}, chunksize=100_000
) as reader:
for chunk in reader:
seen.update(chunk["user_id"].dropna().unique())
print(len(seen))Pitfall 2: dtype drift
pandas infers each column's dtype separately for every chunk. The same column can therefore get different dtypes in different chunks:
- An integer column becomes
float64in any chunk that contains a missing value. - An ID such as
00123becomes the integer123if a chunk happens to contain only digits, which silently drops the leading zeros. - A column that holds numbers in one chunk and a stray text value in another becomes
objectin the second chunk.
Partial results then fail to line up. Group keys of 123 and "123" are different keys, and totals.add(part) produces extra rows. Fix this by declaring dtypes once and using them for every chunk.
import pandas as pd
dtypes = {"customer_id": "string", "region": "string", "amount": "float64"}
with pd.read_csv("sales.csv", dtype=dtypes, chunksize=200_000) as reader:
for chunk in reader:
assert chunk["customer_id"].dtype == "string"Use a nullable or float dtype for any integer column that might contain missing values. If you are unsure which columns are risky, read a sample with nrows and check dtypes. A sample from the top of the file can miss problems that appear later, so make the declared dtypes strict. If a value cannot be converted, read_csv raises an error instead of guessing.
Pitfall 3: accidental full loads
Chunking only saves memory if no object keeps every chunk alive. These patterns quietly load the whole file:
pd.concat(list_of_all_chunks)when you stored every chunk and not just filtered rows.- Calling
reader.read()orlist(reader), which pulls all remaining rows. - Forgetting
chunksize, soread_csvreturns one DataFrame. - Filtering with a condition that keeps almost every row, then collecting the results.
- Appending raw rows to a Python list instead of accumulating summaries.
import pandas as pd
# Memory grows with every chunk: avoid
chunks = [c for c in pd.read_csv("big.csv", chunksize=100_000)]
df = pd.concat(chunks)If the output is too large to keep, write each filtered chunk to disk as you go. If it is small, a collected list of filtered chunks is fine. Estimate the size first, as in the memory-measurement section.
Quick checklist
| Check | Question to ask |
|---|---|
| Statistic | Can I rebuild it from sums, counts, min or max? |
| Dtypes | Did I pass `dtype=` so every chunk has the same types? |
| Memory | Does anything I keep grow with the number of rows read? |
Exercise
A colleague computes the average order value by taking chunk["amount"].mean() for each chunk and then averaging those values. The last chunk has only 50 rows. Why is the result wrong, and what should they keep from each chunk instead?
Show answer
A plain average of chunk means gives the 50-row chunk the same weight as a 200,000-row chunk. They should keep the sum and the count (chunk["amount"].sum() and chunk["amount"].count()) from each chunk, add them across chunks, and divide the total sum by the total count at the end.