Sub topic 13
Chunking and Alternatives When pandas Is Not Enough
This chapter assumes you can read and write pandas code, know what a DataFrame and dtype are, and have worked through the earlier chapters on measuring, vectorizing, choosing dtypes, and loading less data. Here you learn what to do when a well-tuned pandas workflow still does not fit in memory or still runs too slowly.
Recognizing the limit
pandas holds a whole DataFrame in memory, and most operations create temporary copies. A common rule of thumb is that you need several times the size of the data in free RAM. A 2 GB CSV can need 5 to 10 GB while you work with it.
Before moving to other tools, confirm that you have exhausted the cheaper fixes:
- Load only the columns you need with
usecols. - Use compact dtypes such as
category,float32, and small integer types. - Store data in Parquet instead of CSV.
- Remove vectorization problems found by profiling.
If the data still does not fit, or one machine is too slow, you have two broad options. You can process the data in pieces with pandas (chunking), or you can switch to a tool built for larger data.
Symptoms that tell you which problem you have
| Symptom | Likely cause | First thing to try |
|---|---|---|
| `MemoryError`, or the process is killed by the operating system | Data plus temporaries exceed RAM | Chunking, or a lazy or out-of-core library |
| The machine slows down and uses swap | Memory pressure | Reduce columns and dtypes, then chunk |
| CPU stays at 100% on one core for minutes | Single-threaded work | Vectorize, then consider a parallel library |
| Loading takes longer than the analysis | Slow file format | Parquet with column selection |
Check memory use with df.memory_usage(deep=True).sum() before you load the full dataset. You can estimate from a small sample: read 100,000 rows, measure them, and multiply by the ratio of total rows to sample rows.
Chunked reading with read_csv
Passing chunksize to pd.read_csv returns an iterator. Each item is a DataFrame with at most that many rows. Only one chunk is in memory at a time, plus whatever you keep.
import pandas as pd
total_rows = 0
total_amount = 0.0
for chunk in pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
dtype={"region": "category", "amount": "float32"},
chunksize=250_000,
):
total_rows += len(chunk)
total_amount += chunk["amount"].sum()
print(total_rows, total_amount / total_rows)The loop here is over chunks, not rows. Each chunk is still processed with vectorized operations, so the Python overhead is small: a file of 50 million rows with chunksize=250_000 runs the loop only 200 times.
Choosing a chunk size
A chunk should be large enough that vectorized work dominates the loop overhead, and small enough to leave room for temporaries. Values between 100,000 and 1,000,000 rows suit most tables. Measure with perf_counter as in earlier chapters rather than guessing. Very small chunks (a few thousand rows) waste time in per-chunk overhead.
Aggregating across chunks
The key rule is that you must combine partial results in a way that gives the same answer as processing all the data at once. Some statistics combine easily and some do not.
| Statistic | Partial result to keep per chunk | How to combine |
|---|---|---|
| Sum, count, min, max | The same statistic | Sum, sum, min of mins, max of maxes |
| Mean | Sum and count | Total sum divided by total count |
| Variance, standard deviation | Count, sum, sum of squares | Compute from the combined totals |
| Median, quantiles | Not available exactly | Use an approximate method or another tool |
| Distinct count | The set of values | Union the sets (memory grows with distinct values) |
A common error is averaging the per-chunk means. This is wrong when chunks have different sizes, and the last chunk almost always does.
A grouped aggregation follows the same idea. Aggregate each chunk, collect the small results, then aggregate those results again:
import pandas as pd
partials = []
for chunk in pd.read_csv("orders.csv", usecols=["region", "amount"], chunksize=250_000):
part = chunk.groupby("region", observed=True)["amount"].agg(["sum", "count"])
partials.append(part)
combined = pd.concat(partials).groupby(level=0).sum()
combined["mean"] = combined["sum"] / combined["count"]
print(combined)Each partial result has one row per region, so the concatenated frame stays small even when the input is huge. Because sum and count combine by addition, the final mean is exact.
Filtering while reading
Chunking also works as a filter. If you need only a subset of a very large file, keep the matching rows from each chunk and discard the rest:
import pandas as pd
kept = []
for chunk in pd.read_csv("orders.csv", chunksize=250_000):
kept.append(chunk[chunk["amount"] > 1000])
large_orders = pd.concat(kept, ignore_index=True)This uses the list-then-concat pattern from the chapter on building frames. Never call pd.concat inside the loop on a growing result.
Chunked reading from Parquet
pd.read_parquet has no chunksize argument. For Parquet, use pyarrow to read one batch at a time:
import pyarrow.parquet as pq
pf = pq.ParquetFile("orders.parquet")
total = 0.0
for batch in pf.iter_batches(batch_size=250_000, columns=["amount"]):
chunk = batch.to_pandas()
total += chunk["amount"].sum()
print(total)Parquet stores data by column, so requesting columns=["amount"] reads only that column from disk. This is usually faster than chunked CSV reading, which must parse every field of every row.
Limits of chunking
Chunking works well for operations that can be split and recombined. It becomes awkward or impossible in these cases:
- Sorting the whole dataset, because any row can belong anywhere in the output.
- Joins between two large tables, because matching rows can sit in different chunks.
- Exact medians and other order statistics.
- Operations that look at neighbors across chunk boundaries, such as rolling windows. You must carry the last rows of one chunk into the next.
- Anything that needs the whole dataset at once, such as many machine learning fits.
When your task has these properties, writing the recombination logic yourself costs more than adopting a tool that does it for you.
Alternatives to plain pandas
The following libraries cover most needs. They differ in how they scale, so choose by the constraint you actually have.
| Tool | Main idea | Best when | Trade-offs |
|---|---|---|---|
| Polars | Fast DataFrame library in Rust, with lazy queries and multi-threading | Data fits on one machine but pandas is slow | Different API; some pandas code must be rewritten |
| DuckDB | Embedded SQL engine that can query CSV, Parquet, and pandas frames directly | You think in SQL, or need large joins and aggregations on one machine | SQL rather than DataFrame syntax |
| Dask | Splits a DataFrame into many pandas partitions and runs them in parallel | You want pandas-like code on larger-than-memory data or a cluster | Not every pandas feature exists; the scheduler adds overhead |
| PySpark | Distributed engine across a cluster | Data is far beyond one machine | Heavy setup, high overhead on small data |
| Modin | Parallelizes the pandas API on multiple cores | You want minimal code change on one machine | Speedup varies; some operations fall back to plain pandas |
A short DuckDB example
DuckDB can run a grouped query directly on a Parquet file without loading the file into pandas first. Only the result becomes a DataFrame.
import duckdb
result = duckdb.sql("""
SELECT region, SUM(amount) AS total, COUNT(*) AS n
FROM 'orders.parquet'
GROUP BY region
ORDER BY total DESC
""").df()
print(result)DuckDB reads only the columns it needs and processes the file in streaming fashion, so this works on files larger than memory.
A short Polars example
Polars scan_parquet builds a lazy query. Nothing runs until collect(), which lets Polars read only the needed columns and rows.
import polars as pl
result = (
pl.scan_parquet("orders.parquet")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
.collect()
)
print(result)Method names change between Polars versions (for example, older releases used groupby), so check the version you have installed.
Choosing: a decision path
A few practical criteria sit behind this path:
- Prefer the smallest change that solves the measured problem. Chunking an existing script is less work than a rewrite.
- A new library adds a dependency, a new API to learn, and different behavior for missing values and dtypes. Weigh that against the gain.
- Keep Parquet as the shared storage format. Every tool above reads it, so your data stays usable if you change tools later.
- Verify results after every migration, using the same approach as in the chapter on proving the fast version is correct. Convert to pandas and compare with
pd.testing.assert_frame_equal, allowing for small floating-point differences withrtol.
Common errors
- Averaging per-chunk means instead of combining sums and counts.
- Forgetting that
categorycolumns may have different categories in each chunk. Concatenating them can fall back toobjectdtype. Passobserved=Truetogroupbyand consider declaring the categories up front. - Letting an index from each chunk collide. Use
ignore_index=Truewhen concatenating. - Holding references to every chunk, which defeats the purpose. Keep only reduced results.
- Moving to a distributed tool for data that fits in memory. Overhead can make it slower than pandas.
Exercises
Exercise
A file is read in chunks. For each chunk you compute chunk["amount"].mean() and store it. At the end you compute the mean of those stored means. The last chunk has far fewer rows than the others. Why can this give a wrong answer, and what should you store instead?
Show answer
The mean of chunk means gives every chunk equal weight, but chunks with fewer rows should count less. The result differs from the true mean whenever chunk sizes differ. Store each chunk's sum and row count, add them across chunks, and divide the total sum by the total count.
Exercise
You must find the exact median of a column in a 40 GB CSV on a laptop with 16 GB of RAM. Why is plain chunking a poor fit, and name two alternatives.
Show answer
The exact median depends on the sorted order of all values, and partial medians from chunks cannot be combined into the true median. Alternatives: read just that column (for example from Parquet) if it fits in memory, such as 40 GB of rows with one float32 column; or use DuckDB (SELECT median(amount) FROM 'file.parquet') or a Polars lazy query, which handle larger-than-memory data. An approximate quantile method is also acceptable if exactness is not required.
Exercise
Write a loop that reads orders.csv in chunks of 100,000 rows and returns the number of rows where region == "N". Do not keep the chunks.
Show answer
total = 0 for chunk in pd.readcsv("orders.csv", usecols=["region"], chunksize=100000): total += (chunk["region"] == "N").sum() print(total)