Sub topic 10
Choosing a chunk size
This chapter assumes you can read a CSV with pandas.read_csv, loop over a chunksize reader, and use basic groupby aggregation. It covers how to pick the chunksize value and how to check that your choice works.
What the chunk size controls
chunksize is the number of rows in each chunk. It sets the peak memory of your loop, and it also sets how many times pandas must repeat per-chunk work. Two forces pull in opposite directions:
- A small chunk uses little memory, but the loop runs many times. Each iteration has fixed costs, such as building a DataFrame and running a
groupby. - A large chunk runs fewer iterations, but each chunk takes more memory. If it is too large, you are back to the original problem.
There is no universal best value. The right size depends on your row width, your dtypes, and what you do with each chunk.
Estimate memory from a sample
Read a small sample and measure it. This is the same technique from the memory chapter, now used to pick a number.
import pandas as pd
sample_rows = 100_000
sample = pd.read_csv("big.csv", nrows=sample_rows)
sample_mib = sample.memory_usage(deep=True).sum() / 1024**2
bytes_per_row = sample.memory_usage(deep=True).sum() / sample_rows
print(f"{sample_mib:.1f} MiB for {sample_rows} rows")
print(f"{bytes_per_row:.0f} bytes per row")Use deep=True so that string (object) columns are measured by their real contents, not just their pointers.
Turn a memory budget into a row count
Decide how much memory a single chunk may use. Then divide by bytes per row. Leave generous headroom, because the work you do on a chunk creates copies. A filter, a groupby, or a type conversion can each add a temporary object of similar size.
A common rule of thumb is to budget a chunk at no more than about one tenth of your available memory.
import pandas as pd
sample_rows = 100_000
sample = pd.read_csv("big.csv", nrows=sample_rows)
bytes_per_row = sample.memory_usage(deep=True).sum() / sample_rows
chunk_budget_mib = 200
chunk_rows = int(chunk_budget_mib * 1024**2 / bytes_per_row)
print(chunk_rows)Then pass chunk_rows as chunksize. If you have already applied usecols and dtype, measure the sample with those options too. Otherwise the estimate will be too high, and your chunks will be smaller than they need to be.
import pandas as pd
reader = pd.read_csv(
"big.csv",
usecols=["id", "amount"],
dtype={"id": "int32", "amount": "float32"},
nrows=100_000,
)
print(reader.memory_usage(deep=True).sum() / 1024**2, "MiB")Rules of thumb
| Situation | Suggested direction |
|---|---|
| Wide rows, many text columns | Smaller chunks (tens of thousands of rows) |
| Narrow numeric rows, small dtypes | Larger chunks (hundreds of thousands to millions of rows) |
| Heavy per-chunk work such as joins | Smaller chunks, because of temporary copies |
| Light work such as counting | Larger chunks, to cut loop overhead |
| Very slow disk or network storage | Larger chunks, so each read does more useful work |
For many files, anything from 50,000 to 1,000,000 rows is a sensible starting range. Treat it as a starting point and verify it.
Verify by measuring
Time a short run with different sizes and watch peak memory in your system monitor. This script times the first few chunks for several candidate sizes.
import time
import pandas as pd
for size in [10_000, 100_000, 1_000_000]:
start = time.perf_counter()
rows = 0
with pd.read_csv("big.csv", chunksize=size) as reader:
for i, chunk in enumerate(reader):
rows += len(chunk)
if rows >= 2_000_000:
break
elapsed = time.perf_counter() - start
print(f"chunksize={size:>9,} rows={rows:>9,} {elapsed:.2f}s")Each run reads about the same number of rows, so the times are comparable. Usually the time drops quickly as chunks grow, then flattens. Pick the point where it flattens, not the largest size that fits.
Common mistakes
- Measuring the sample without your final options. Estimate with the same
usecolsanddtypethat the real run uses. - Using the first rows as typical. If row sizes change later in the file, such as longer text, the first sample underestimates memory. Add headroom.
- Ignoring the cost of the work done per chunk. The chunk is not the only object in memory.
- Tuning too finely. A difference between 200,000 and 250,000 rows rarely matters. Stop when memory is safe and speed is reasonable.
Exercise
A sample of 50,000 rows measured with memory_usage(deep=True) takes 100 MiB. You want each chunk to use about 400 MiB at most. Roughly what chunksize should you use, and why might you choose a smaller value?
Show answer
100 MiB for 50,000 rows is 2 MiB per 1,000 rows, so 400 MiB allows about 200,000 rows. You might choose a smaller value because filtering, grouping, or type conversion creates temporary copies of the chunk, so peak memory is higher than the chunk alone. Later rows might also be wider than the sample.