Bigger data: Polars and DuckDB
Last updated
pandas keeps the whole table in memory, which is fine until the table is bigger than your computer's memory. In this lesson you'll measure what a table really costs, shrink it, read a big file in pieces, and meet the two tools to reach for when pandas runs out: Polars and DuckDB.
By the end of this lesson you can
- Measure a table’s memory, and shrink it with smaller types
- Read a big CSV in chunks and combine the results
- Say what Parquet and Apache Arrow are for
- Recognise the same question written in pandas, Polars and DuckDB
What a table costs
200,000 rows of sales: a store name, kilos and a price. Run the cells.
About 9.5 MB as read. Most of it is the store names: each row keeps its own copy of the text. With the types chosen on purpose, the same table is 1.4 MB:
storeascategory(lesson 4.9): each name once, and a small code per row.kilosasint16: whole numbers up to 32,767, 2 bytes instead of 8 (lesson 2.3, and check the range first).priceasfloat32: 4 bytes instead of 8, with about 7 significant digits, plenty for prices.
memory_usage(deep=True) counts everything; without deep=True, pandas only counts the pointers to the text and the answer looks far too small. Reading only the columns you need, with usecols in read_csv, saves even more.
A rule of thumb from the pandas documentation: pandas needs 5 to 10 times a file's size in memory to work on it comfortably.
Reading in chunks
If a summary is all you need, you don't need the whole table at once. Step through, then run it.
read_csv(..., chunksize=10_000) reads it 10,000 rows at a time.chunksize=10_000 makes read_csv give you the file 10,000 rows at a time. Each chunk is summed by store and added to a running total, then thrown away. The last cell checks that the answer is the same as reading everything at once.
This works for sums, counts, minimums and maximums, which can be built up piece by piece. A mean needs the sums and the counts kept separately and divided at the end, and a median can't be done this way at all: it needs every value.
Polars and DuckDB
When chunks get awkward, there are tools built for data bigger than memory. Here's one question, revenue by store, in each. These run on your own computer (pip install polars duckdb); they're not loaded into this page.
pandas
sales = pd.read_csv("sales.csv")
(sales.assign(revenue=sales["kilos"] * sales["price"])
.groupby("store")["revenue"].sum())Polars, a DataFrame library written in Rust:
import polars as pl
(pl.scan_csv("sales.csv")
.with_columns(revenue=pl.col("kilos") * pl.col("price"))
.group_by("store").agg(pl.col("revenue").sum())
.collect())DuckDB, a database that runs inside Python with no server:
import duckdb
duckdb.sql("""
SELECT store, SUM(kilos * price) AS revenue
FROM 'sales.csv'
GROUP BY store
""").df()What they share: both use all your processor's cores, and both can be lazy. scan_csv and DuckDB's FROM 'sales.csv' don't load the file; they read the question first, then read only the columns and rows it needs, in pieces. DuckDB answers in SQL, which lesson 5.3 teaches, and its .df() hands back a pandas table.
Two file formats make all of this faster:
- Parquet (lesson 3.3) stores a table by column, compressed, with its types. Reading two columns of a Parquet file reads only those two. A CSV has to be read in full.
- Apache Arrow is a way of laying out columns in memory that pandas, Polars and DuckDB all understand, so they can hand tables to each other without copying.
A good habit for big data: convert the CSV to Parquet once, then query the Parquet file with DuckDB or Polars, and bring the small answer into pandas.
Wrong way: a 5 GB file on an 8 GB laptop
A year of transactions from every store arrives: a 5 GB CSV. pd.read_csv("transactions.csv") on an 8 GB laptop.
By the 5-to-10-times rule, pandas needs 25 to 50 GB. The laptop has 8, some of it used by the system and the browser. What happens: the computer slows to a crawl as it swaps memory to disk, and then Python stops with a MemoryError, or the notebook's kernel simply dies and restarts, losing everything in memory. Sometimes it takes many minutes to fail.
What to do instead, in order of effort:
- Read less:
usecolsfor only the columns you need, and the rightdtypefor each, as in step 1. - Read in chunks if the answer is a sum or a count, as in step 2.
- Convert to Parquet once, in chunks, and query it with DuckDB or Polars, which never hold the whole file.
- Ask for less data: often a month, or a summary, answers the question.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- pandas: Scaling to large datasets: fewer columns, smaller types, chunks, and other libraries
- pandas: IO tools, iterating through files chunk by chunk: chunksize
- Raasveldt and Mühleisen, DuckDB: an Embeddable Analytical Database, SIGMOD 2019: what DuckDB is, from the people who made it
- Pyodide: Packages built in Pyodide: which libraries can run inside a browser