Sub topic 13
When Chunking Is Not Enough: Dask, Polars and DuckDB
This chapter assumes you can write the chunked patterns from earlier chapters: read_csv with chunksize, per-chunk filtering, and combining partial aggregates. It also assumes you know basic pandas groupby. You don't need prior experience with the three tools below. The goal is to help you decide when to leave chunked pandas, and to show what the same job looks like in each tool.
Where chunked pandas runs out
Chunking works well for jobs where each chunk can be reduced independently and the partial results combine cleanly. Some jobs strain that model:
- Statistics that don't combine. An exact median, an exact quantile, or a count of distinct values needs the whole column, or a clever data structure, not simple partial sums.
- Joins and sorts on big data. Sorting 50 GB of rows needs an external merge sort. Joining two large files needs one side to fit in memory, or both sides to be partitioned by key. Hand-written chunk loops for either are slow to write and easy to get wrong.
- Speed. A chunk loop runs on one CPU core. Parsing CSV in pandas is mostly single-threaded, so a 20 GB file can take many minutes even though memory is fine.
- Growing code. Once you maintain a dictionary of partial states, a merge function and a special case for the last chunk, you are building a query engine by hand.
Three tools cover these cases. Each one does the chunking for you, so you describe the result you want and the engine decides how to stream the data.
Dask: pandas-style code on partitioned data
Dask splits a dataset into partitions, each of which is a pandas DataFrame. It builds a graph of tasks lazily, then runs them in parallel on threads, processes, or a cluster when you call .compute().
import dask.dataframe as dd
df = dd.read_csv(
"sales-*.csv",
usecols=["region", "amount"],
dtype={"region": "string", "amount": "float64"},
blocksize="64MB",
)
result = df.groupby("region")["amount"].agg(["sum", "count", "mean"]).compute()
print(result)Points to know:
blocksizecontrols partition size. Smaller partitions use less memory per task but add scheduling overhead. 64 MB to a few hundred MB is a typical range.- Pass
dtypeexplicitly. Dask infers types from a sample of the first partition, so a column that looks like integers at the top and contains text later fails halfway through the job. This is the same dtype drift problem you saw with chunks, now hidden inside a parallel run. - Nothing runs until
.compute(),.persist()or a write such as.to_parquet(). A.compute()on a result that is still huge brings it all into memory, so reduce first. - Dask implements approximate versions of some operations, for example
quantileandnunique_approx. Read the docs for each operation to see whether the result is exact.
Dask is the best fit when your code already uses pandas idioms, when you have many files, or when you may later scale from one laptop to a cluster. It is not the fastest option on a single machine for a single file.
Polars: a lazy, multi-threaded engine
Polars is a DataFrame library written in Rust. Its lazy API, scan_csv, builds a query plan instead of loading data. The optimizer pushes column selection and filters down into the reader, so only the needed columns and rows are materialized. Polars uses all CPU cores.
import polars as pl
query = (
pl.scan_csv("sales.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(
pl.col("amount").sum().alias("sum"),
pl.col("amount").count().alias("count"),
pl.col("amount").mean().alias("mean"),
)
.sort("region")
)
print(query.explain())
result = query.collect(engine="streaming")
print(result)explain() prints the optimized plan, which is useful for checking that only the region and amount columns are read. engine="streaming" asks Polars to process the data in batches rather than all at once. This form needs a recent Polars release. Older releases used collect(streaming=True), and the streaming engine does not support every operation. When an operation is not supported, Polars may fall back to loading more data, so test with your real file and watch memory.
Differences from pandas that catch people out:
- The method is
group_by, notgroupby. - Polars has no row index. Code that relies on
df.loc[label]or index alignment must be rewritten. - Expressions such as
pl.col("amount") > 0replace boolean masks likedf["amount"] > 0. - You can convert at the edge with
result.to_pandas()when the reduced result is small and you want to continue in pandas.
Polars is a good choice when one machine is enough, you want speed, and you are willing to learn a new expression API.
DuckDB: SQL over files
DuckDB is an in-process analytical database. There is no server to install or run. It reads CSV and Parquet directly, executes queries in parallel, and can spill intermediate results to disk when a query exceeds its memory limit. That makes it strong for sorts, joins and exact statistics on files larger than RAM.
import duckdb
duckdb.sql("SET memory_limit = '4GB'")
result = duckdb.sql(
"""
SELECT
region,
sum(amount) AS total,
count(amount) AS n,
avg(amount) AS mean,
median(amount) AS median
FROM read_csv('sales.csv')
WHERE amount > 0
GROUP BY region
ORDER BY region
"""
).df()
print(result)The median column is the statistic that chunked pandas could not compute exactly with simple partial results. DuckDB does it for you. The .df() call converts the result to a pandas DataFrame, so it should be small by then.
DuckDB can also write the result without ever bringing it into Python:
import duckdb
duckdb.sql(
"""
COPY (
SELECT *
FROM read_csv('events.csv')
WHERE status = 'error'
) TO 'errors.parquet' (FORMAT parquet)
"""
)This replaces the filter-and-append loop from the earlier chapter with one statement. It also converts the output to Parquet, which is smaller and faster to read back than CSV.
Comparing the options
| Tool | Style | Parallelism | Best for | Main cost |
|---|---|---|---|---|
| Chunked pandas | Python loop | One core | Filters, sums, counts, simple group-bys | You write the combine logic |
| Dask | pandas-like API, lazy | Threads, processes, cluster | Many files, existing pandas code, scale-out | Scheduler overhead, partial pandas compatibility |
| Polars | Expression API, lazy | All cores on one machine | Fast single-machine pipelines | New API, streaming gaps |
| DuckDB | SQL | All cores, spills to disk | Joins, sorts, exact medians, ad hoc queries | Needs SQL, type inference on CSV |
Failure modes shared by all three
- Calling the final step too early.
.compute(),.collect()and.df()all load the result into memory. Reduce first with a filter, aggregate orLIMIT. - Reading CSV when you could read Parquet. CSV is text, has no stored types and cannot skip columns cheaply. If you query the same data more than once, convert it once to Parquet and query that.
- Assuming the tool is automatically fast. A query with a huge number of distinct group keys, or a join on two huge tables, can still run out of memory. Check each tool's memory settings and use
explainor equivalent. - Switching too soon. A 3 GB CSV with a filter and a sum is a 15-line chunked pandas job. A new dependency adds installation, learning and debugging cost. Move when the chunk code becomes the harder part of the job.
A practical rule
Start with the cheapest approach that fits. Use usecols and dtype first, then chunked pandas. If the job needs exact non-combinable statistics, large joins or sorts, or its runtime is too long, try DuckDB when you like SQL and Polars when you like DataFrame code. Choose Dask when you need pandas-compatible code over many files or a cluster.
Exercise
You must compute the exact median of the amount column in a 40 GB CSV on a laptop with 16 GB of RAM. Why is a chunked pandas loop a poor fit, and which tool from this chapter would you try first?
Show answer
The median of per-chunk medians is not the median of the whole column, so the per-chunk results cannot be combined, and an exact median needs all values (or a sort). DuckDB is a good first choice: SELECT median(amount) FROM read_csv('big.csv') runs in parallel and can spill to disk when needed. Polars lazy mode with the streaming engine is another option.
Exercise
A Dask job reads many CSV files and fails midway with a type error on a column that looks numeric in the first partition. What is the likely cause, and how do you fix it?
Show answer
Dask infers dtypes from a sample of the first partition, and later partitions contain values that do not fit (for example text in an integer column). Pass an explicit dtype mapping to dd.read_csv, such as dtype={"amount": "float64"}, or read the column as a string and convert it after cleaning.
Exercise
What is the difference between calling .collect() on a Polars lazy query and calling .collect(engine="streaming"), and why should you still reduce the data before collecting?
Show answer
Plain .collect() runs the optimized plan with the standard in-memory engine, while engine="streaming" processes the data in batches so peak memory can be lower. In both cases the final result is a full in-memory DataFrame, so a result that is still huge (for example an unfiltered select of all rows) can still run out of memory. Filter and aggregate in the query first.