Sub topic 11
Pitfalls: non-combinable statistics, dtype drift and accidental full loads
This chapter assumes you can read a CSV in chunks with chunksize, loop over the reader, and aggregate with groupby. It covers three mistakes that produce wrong numbers or memory errors in chunked code. Two of them fail silently.
Pitfall 1: statistics that cannot be combined
A chunked job computes a small result per chunk and merges the results at the end. The merge only works if the statistic can be rebuilt from partial values. Sums, counts, minimums and maximums can. A mean can too, but only if you keep its sum and count. A median, a mode and a percentile cannot be rebuilt from per-chunk medians, modes or percentiles.
| Statistic | Combinable from per-chunk results? | What to keep per chunk |
|---|---|---|
| sum, count | Yes | the sum, the count |
| min, max | Yes | the min, the max |
| mean | Yes | sum and count, not the per-chunk mean |
| variance, std | Yes | count, sum and sum of squares |
| distinct count | Only with extra state | the set of values seen |
| median, percentiles | No | an approximation, or a different tool |
| mode | Partly | full value counts per chunk |
Averaging the averages
Chunks rarely have equal sizes, and the last one is usually smaller. Averaging per-chunk means gives every chunk the same weight regardless of its row count.
import pandas as pd
chunk_a = pd.Series([10, 20, 30, 40, 50, 60, 70, 80, 90])
chunk_b = pd.Series([100])
wrong = (chunk_a.mean() + chunk_b.mean()) / 2
right = (chunk_a.sum() + chunk_b.sum()) / (len(chunk_a) + len(chunk_b))
print(wrong) # 75.0
print(right) # 55.0The wrong answer looks plausible, so no error alerts you. Always carry the sum and the count and divide once at the end.
Variance and standard deviation
These need three running values: the row count n, the sum s, and the sum of squares ss. After the last chunk, the sample variance is (ss - s**2 / n) / (n - 1).
import pandas as pd
n = 0
s = 0.0
ss = 0.0
with pd.read_csv("sales.csv", usecols=["amount"], chunksize=200_000) as reader:
for chunk in reader:
a = chunk["amount"].dropna().astype("float64")
n += len(a)
s += a.sum()
ss += (a ** 2).sum()
variance = (ss - s ** 2 / n) / (n - 1)
print(variance ** 0.5)Distinct counts
Adding per-chunk nunique() values double-counts any value that appears in more than one chunk. Keep a set of the values seen and take its length at the end.
import pandas as pd
seen = set()
with pd.read_csv("events.csv", usecols=["user_id"], chunksize=100_000) as reader:
for chunk in reader:
seen.update(chunk["user_id"].dropna().unique())
print(len(seen))The set grows with the number of distinct values, not with the number of rows. That is fine for a million users but not for a billion distinct strings. For very high cardinality, use a sketch such as HyperLogLog, or hand the job to DuckDB or Polars.
Medians, percentiles and modes
There is no exact way to get a median from per-chunk medians. You have three practical options:
- Build a histogram. Read the column once to find the min and max, then count values per bin in a second pass, and locate the median bin. This is exact to the bin width.
- Accept an approximation from a streaming sketch library such as t-digest.
- Use a tool that sorts out of core, such as DuckDB's
median()or Dask's approximate quantiles.
For a mode, keep value_counts() per chunk and add them together as you do with grouped sums. This is exact, but memory grows with the number of distinct values.
Grouped results can lose rows
Grouped merging has its own traps. By default groupby drops rows whose key is missing. If missing keys matter, use groupby("region", dropna=False). When you merge partial results with add(part, fill_value=0), a key missing from one chunk is treated as zero, which is correct for sums and counts. It is wrong for min and max. Merge those with pd.concat([totals, part]).groupby(level=0).min() instead.
Pitfall 2: dtype drift
When you omit dtype, pandas infers each column's type separately for every chunk. The same column can therefore come back as int64 in one chunk and float64 or object in another. This is called dtype drift.
import io
import pandas as pd
text = "id,score\n1,10\n2,20\n3,\n4,40\n"
with pd.read_csv(io.StringIO(text), chunksize=2) as reader:
for chunk in reader:
print(chunk["score"].dtype)This prints int64 for the first chunk and float64 for the second. The second chunk contains a missing value, and int64 cannot hold one. A merge or concat across chunks then upcasts silently, and sums of large integers can lose precision as floats. Text is worse. If one chunk contains "N/A" in a numeric column, that chunk becomes object, and arithmetic on it either fails or produces strings.
Declare types up front so every chunk gets the same ones:
import io
import pandas as pd
text = "id,score\n1,10\n2,20\n3,\n4,40\n"
with pd.read_csv(io.StringIO(text), chunksize=2, dtype={"score": "Int64"}) as reader:
for chunk in reader:
print(chunk["score"].dtype)Both chunks now report Int64, pandas' nullable integer type. Related drift traps:
- Identifiers with leading zeros. A ZIP code such as
02134becomes the integer2134in a numeric chunk. Declare it as"string"orstr. - Dates. A date column stays text unless you pass
parse_dates. Chunks that happen to contain no unusual values may behave differently from those that do. - Categoricals.
dtype="category"builds categories per chunk, so chunks end up with different category sets. Concatenating them falls back toobject. Usepd.CategoricalDtype(categories=[...])with a fixed list. - Marker strings. Pass
na_values=["N/A", "-"]so those markers become missing values instead of forcing a column toobject.
Avoid low_memory=False as a fix. It makes pandas parse the whole file before inferring types, which defeats the purpose of reading in pieces.
Pitfall 3: accidental full loads
Chunking only saves memory if you never hold all the chunks at once. Several patterns quietly bring the whole file into memory.
import pandas as pd
# Each of these loads everything:
chunks = list(pd.read_csv("big.csv", chunksize=100_000))
df = pd.concat(pd.read_csv("big.csv", chunksize=100_000))
df = pd.read_csv("big.csv", chunksize=100_000).read()list(reader) keeps every chunk alive. pd.concat over the reader builds the full DataFrame, often with a temporary second copy during the join. The read() method on the reader returns all remaining rows. These calls are fine on a small test file and then fail on the real one.
A second group of mistakes keeps data alive between iterations:
- Appending every
chunkto a list "to use later". - Storing each chunk in a dictionary, or assigning it to a variable defined outside the loop, such as
previous = chunk, and never replacing it. - Collecting filtered rows when the filter matches most of the file. Estimate the match rate on a sample first. If the result could be large, write it to disk, as in the incremental-writing pattern.
A third group needs the whole dataset by nature:
- Sorting by a column,
sort_values, across the entire file. - Global
drop_duplicates(). Duplicates in different chunks are not detected unless you keep a set of keys seen so far. - A
groupbyon a key with nearly one value per row. The partial result then has almost as many rows as the input.
The healthy pattern holds one chunk plus a small accumulator:
import pandas as pd
matches = 0
with pd.read_csv("events.csv", usecols=["status"], dtype={"status": "category"},
chunksize=100_000) as reader:
for chunk in reader:
matches += (chunk["status"] == "error").sum()
print(matches)Here the loop keeps a single integer between chunks, and usecols reads only the needed column.
Rows that cross chunk boundaries
Chunk edges fall at arbitrary row numbers. Operations that look at neighboring rows, such as diff, shift, rolling or "the previous event for this user", are wrong at the first row of every chunk. A group's rows can also be split across two chunks. Carry the last few rows of one chunk into the start of the next:
import pandas as pd
tail = None
with pd.read_csv("readings.csv", usecols=["value"], chunksize=100_000) as reader:
for chunk in reader:
window = chunk if tail is None else pd.concat([tail, chunk], ignore_index=True)
deltas = window["value"].diff()
if tail is not None:
deltas = deltas.iloc[len(tail):]
# use deltas here
tail = chunk.tail(1)If the logic needs more context than a small overlap, a chunked approach is probably the wrong tool.
Small output mistakes
- Writing the header for every chunk puts header lines in the middle of the output file. Write it only for the first chunk.
- Opening the output with
mode="w"for every chunk overwrites earlier results. Use"a"after the first chunk. - Leaving
index=Falseout writes the index column, which then reloads as an extra column.
Checklist before running on the real file
- Does every statistic come from sums, counts, min, max or a set, rather than from per-chunk answers?
- Are
dtype,parse_datesandna_valuesset explicitly? - Is there any
list(reader),concatover the reader, orread()? - Does anything stored between iterations grow with the file size?
- Do any operations depend on row order or on groups that may span chunks?
Exercise
A job reads sales.csv in chunks of 100,000 rows. Chunk 1 has mean amount 40 over 100,000 rows. The final chunk has mean 90 over 20,000 rows. What is the correct overall mean for these two chunks, and what does averaging the two chunk means give instead?
Show answer
The correct mean is (40 100,000 + 90 20,000) / 120,000 = 5,800,000 / 120,000, which is about 48.33. Averaging the two chunk means gives (40 + 90) / 2 = 65, which overweights the small last chunk. Keep each chunk's sum and count, add them up, and divide once at the end.
Exercise
A numeric column qty is read as int64 in most chunks but as object in one chunk, which breaks your sum. Name two causes and give the read_csv arguments that fix the problem.
Show answer
Likely causes are marker strings such as "N/A" or "-" in that chunk, or stray text values. Fix it by passing dtype={"qty": "Int64"} (or "float64") and na_values=["N/A", "-"], so the markers become missing values and every chunk gets the same type.
Exercise
Which of these lines can exhaust memory on a file larger than RAM: total += chunk["amount"].sum(), all_chunks.append(chunk), pd.concat(reader)? Explain why.
Show answer
all_chunks.append(chunk) and pd.concat(reader) both end up holding every chunk, and therefore the whole file, in memory. total += chunk["amount"].sum() keeps only one number between iterations, so memory stays at about one chunk.