Sub topic 13
When chunking is not enough: Dask, Polars and DuckDB
This chapter assumes you can write chunked read_csv loops, combine partial groupby results, and know the limits of statistics that cannot be combined. Here you learn when to stop hand-writing chunk loops and switch tools.
Where chunking starts to hurt
Chunking works well for filters, sums, counts and means. The cost is code you must maintain yourself. These situations make that cost too high:
- The job needs joins between two large files.
- You need exact medians, percentiles or distinct counts over the whole file.
- You need sorting or window functions across the full data.
- The same job runs often and the single-threaded loop is too slow.
- The result of a step is itself too big for memory.
A chunk loop reads one piece at a time and uses one CPU core. The tools below plan the whole query, read only the columns they need, and run in parallel.
DuckDB: SQL directly on files
DuckDB is an embedded analytical database that runs inside your Python process. It can query a CSV or Parquet file without loading it into a DataFrame first. It spills to disk when an operation does not fit in memory.
import duckdb
result = duckdb.sql("""
SELECT region,
SUM(amount) AS total,
AVG(amount) AS mean
FROM read_csv('sales.csv')
GROUP BY region
""").df()
print(result)This replaces the whole sum-and-count loop from earlier chapters. Only the small result becomes a pandas DataFrame, through .df().
Polars: lazy queries
Polars is a DataFrame library written in Rust. Its scan_csv function builds a lazy query instead of reading the file. Polars optimizes the plan, so it reads only the columns the query uses and applies filters early.
import polars as pl
result = (
pl.scan_csv("sales.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(
pl.col("amount").sum().alias("total"),
pl.col("amount").mean().alias("mean"),
)
.collect()
)
print(result)Nothing runs until collect(). For inputs larger than memory, Polars has a streaming engine that processes the data in batches. Check your installed version's documentation for how to enable it, because the option name has changed between releases.
Dask: pandas-style code across many partitions
Dask splits a dataset into partitions and processes them in parallel, on one machine or on a cluster. Its API closely follows pandas.
import dask.dataframe as dd
df = dd.read_csv("sales_*.csv", usecols=["region", "amount"])
result = df.groupby("region")["amount"].agg(["sum", "count"]).compute()
print(result)Dask is also lazy: compute() triggers the work. It does the partial-result combining that you wrote by hand.
Choosing a tool
| Tool | Best for | Trade-off |
|---|---|---|
| pandas chunks | One-off filters and simple aggregates | You write and test the combining logic |
| DuckDB | SQL-style aggregation, joins and sorting on files | Needs SQL; works best on one machine |
| Polars | Fast single-machine pipelines with a DataFrame API | A different API from pandas |
| Dask | Existing pandas code, many files, clusters | Scheduler overhead; some pandas features are missing |
Common mistakes
- Calling
.compute()or.collect()on an unfiltered, unaggregated query. This loads the full dataset and brings back the memory error you were avoiding. - Switching tools for a job that a 15-line chunk loop already handles.
- Assuming results match pandas exactly. Null handling, sort order and dtype inference can differ, so compare a small sample first.
Exercise
You must join two 40 GB CSV files on a customer ID and compute the exact median order value per customer segment, on one laptop. Why is a pandas chunk loop a poor fit, and which tool would you try first?
Show answer
A join needs matching rows from both files, and an exact median cannot be built by combining per-chunk medians, so a chunk loop would need complex manual logic. DuckDB is a good first choice. It runs the join and median in SQL on the files directly and can spill to disk. Polars is also reasonable.