Sub topic 3
Combining Grouped Results from Many Chunks
Assume you know Python loops, pandas DataFrames, read_csv, and basic groupby operations. Chunked processing means that each chunk must produce a partial result that can be combined with other partial results.
Combine sums and counts
For a mean, do not average the means from each chunk. A chunk with 10 rows and a chunk with 1,000 rows must not have equal weight. Store each group’s sum and count, then calculate the mean once at the end.
import pandas as pd
totals = None
with pd.read_csv(
"sales.csv",
usecols=["region", "amount"],
chunksize=200_000,
) as reader:
for chunk in reader:
partial = chunk.groupby("region")["amount"].agg(
total="sum",
count="count",
)
totals = partial if totals is None else totals.add(
partial, fill_value=0
)
totals["mean"] = totals["total"] / totals["count"]
print(totals)The same pattern works for totals, counts, and other additive measures.
Choose a chunk size
Start with a size such as 50,000 or 100,000 rows. Measure a representative sample with memory_usage(deep=True), then increase the size if processing is too slow. Leave memory for pandas overhead, grouping, and the rest of your program.
Avoid common pitfalls
- Median, exact percentile, and some distinct-count calculations cannot be combined by simply adding chunk results. Use a suitable algorithm or a second pass.
- Columns can receive inconsistent inferred dtypes across chunks. Pass an explicit
dtypewhen possible. - Do not call
pd.read_csv("large.csv")elsewhere in the program. One accidental full load defeats chunking. - Keep only the partial result you need. Appending every matching chunk to a list can recreate the memory problem.
Other data sources
SQL queries can return an iterator with chunksize:
for chunk in pd.read_sql_query(query, connection, chunksize=100_000):
process(chunk)JSON Lines files support pd.read_json("events.jsonl", lines=True, chunksize=100_000). For Parquet, use PyArrow’s ParquetFile.iter_batches, then convert each batch to a DataFrame.
When chunking is not enough
Use Dask when you want a pandas-like API with distributed or parallel execution. Use Polars for a fast DataFrame engine and lazy queries. Use DuckDB when SQL is convenient, especially for querying Parquet directly. These tools can provide better query planning and parallelism than a hand-written loop.
Exercise
Why should grouped means be calculated from combined sums and counts instead of averaging chunk means?
Show answer
Chunk means may represent different numbers of rows. Combining sums and counts gives every row its correct weight.