Sub topic 13
Chunking and alternatives when pandas is not enough
This chapter assumes you can read a CSV with read_csv, use groupby, and know that pandas holds a whole DataFrame in memory. The earlier chapters in this tutorial covered the speed fixes. This one covers what to do when the data itself is the problem.
Signs that pandas is the wrong fit
Tuning helps only up to a point. Stop tuning when you see these signs:
read_csvraisesMemoryError, or the operating system kills the process.- The file is larger than about a third of your RAM. Many pandas operations make temporary copies, so you need spare room.
- You already use vectorized code, compact dtypes, and
usecols, and the step is still too slow or too big.
At that point you have two options. You can process the data in pieces, or you can switch to a tool built for larger data.
Chunking with read_csv
The chunksize argument makes read_csv return an iterator. Each item is a DataFrame with at most that many rows. Only one chunk is in memory at a time.
The rule for chunking is that each chunk must produce a small partial result, and you must be able to combine the partial results. Sums and counts combine easily. A mean does not, because you cannot average averages. Keep the sum and the count, then divide at the end.
import numpy as np
import pandas as pd
# Create a sample file so this example runs on its own.
rng = np.random.default_rng(0)
pd.DataFrame({
"order_id": np.arange(1_000_000),
"region": rng.choice(["N", "S", "E", "W"], size=1_000_000),
"amount": rng.random(1_000_000) * 100,
}).to_csv("orders.csv", index=False)
partials = []
reader = pd.read_csv(
"orders.csv",
usecols=["region", "amount"],
dtype={"amount": "float32"},
chunksize=250_000,
)
for chunk in reader:
partials.append(chunk.groupby("region")["amount"].agg(["sum", "count"]))
combined = pd.concat(partials).groupby(level=0).sum()
combined["mean"] = combined["sum"] / combined["count"]
print(combined)Each chunk is reduced to at most four rows before the next chunk loads. The final groupby(level=0) adds the partial sums and counts for each region.
Chunking has limits. Operations that need all rows at once are awkward, for example a global sort, a median, or a join between two large tables. You can write these by hand, but at that point a different tool is usually cheaper.
Alternatives
| Tool | What it is | Use it when |
|---|---|---|
| Parquet with PyArrow | Columnar file format and reader | You only need some columns or row groups from a file. |
| Polars | DataFrame library with a multithreaded, lazy query engine | The data fits on one machine, but pandas is slow or memory-heavy. |
| DuckDB | In-process SQL engine that reads CSV and Parquet directly | You prefer SQL, or the data is larger than RAM. It can spill to disk. |
| Dask | Splits a DataFrame into many pandas partitions and runs them in parallel | You want pandas-like code across all cores or several machines. |
| Spark | Cluster computing framework | The data lives on a cluster and is far beyond one machine. |
A DuckDB query on the file from above looks like this:
import duckdb
result = duckdb.sql("""
SELECT region, SUM(amount) AS total, AVG(amount) AS mean
FROM 'orders.csv'
GROUP BY region
ORDER BY region
""").df()
print(result)DuckDB reads the file in a streaming fashion, and .df() returns the small result as a pandas DataFrame. You can use it for the heavy step and keep pandas for the rest.
Choosing a path
Apply the same discipline as in the rest of this tutorial. Measure first, then switch. Compare the new tool's output with the pandas output on a small sample, as you did with assert_series_equal. A new library can differ in null handling, sort order, and dtypes.
Exercise
You need the mean amount per region from a 40 GB CSV on a laptop with 16 GB of RAM. A colleague suggests averaging each chunk's mean and then averaging those results. What is wrong with this, and what should you store per chunk instead?
Show answer
Chunks can have different row counts per region, so an average of chunk means weights every chunk equally and gives the wrong answer. Store the sum and the count for each region in every chunk, add them across chunks, and divide the total sum by the total count at the end.
Exercise
Name two cases where chunking with chunksize is a poor choice and a tool such as DuckDB or Polars is a better one.
Show answer
Any two of: a global sort, an exact median, or a join between two large tables. These operations need all rows at once, so partial results from each chunk cannot be combined simply.