Sub topic 10
Choosing a chunk size
This chapter assumes you can write a loop over pd.read_csv(..., chunksize=...), know what usecols and dtype do, and have used memory_usage(deep=True). Here you will learn how to pick a chunksize value on purpose instead of copying 100_000 from an example.
What the chunk size controls
chunksize is the number of rows in each DataFrame the reader yields. It is a row count, not a byte count. Two files with the same row count can need very different amounts of memory per chunk, because memory depends on the columns, their dtypes, and the length of any strings.
The value trades two costs against each other:
- A small chunk keeps peak memory low. It also means more loop iterations, and each iteration has fixed overhead: parsing setup, building a DataFrame, and running your per-chunk code.
- A large chunk amortizes that overhead and lets vectorized operations work on more data at once. It also raises peak memory and risks the same failure you were trying to avoid.
Performance is usually flat across a wide middle range. Going from 10,000 to 1,000,000 rows per chunk often changes total time by tens of percent, not by orders of magnitude. The cost that matters most is hitting the memory limit, so size the chunk by memory first and tune speed second.
Step 1: Estimate memory per row
Read a sample and measure it. This is the same technique from the measuring chapter, now used to compute a budget.
import pandas as pd
sample = pd.read_csv("big.csv", nrows=100_000)
total_bytes = sample.memory_usage(deep=True).sum()
bytes_per_row = total_bytes / len(sample)
print(f"{bytes_per_row:.1f} bytes per row")
print(sample.dtypes)deep=True matters. Without it, pandas counts only the pointer for each string in an object column and not the string itself, so the number can be several times too small.
Use the same usecols and dtype you plan to use in the real run. Measuring a sample that loads every column as default dtypes, then reading with a narrower setup, gives you an estimate that is too pessimistic. Measuring with a narrow setup and then reading with a wide one gives an estimate that is too optimistic and may crash.
Step 2: Set a memory budget
Decide how much memory one chunk may use. The chunk is not the only thing in memory, so leave room for:
- The Python interpreter and imported libraries.
- Temporary copies. A filter like
chunk[chunk["status"] == "error"]builds a boolean mask and a new DataFrame. Agroupbyallocates intermediate arrays. Operations such assort_valuesandmergecan briefly need two or three times the chunk size. - Accumulated results, such as a list of filtered chunks or a growing totals table.
- Other processes on the machine.
A workable rule is to budget a chunk at roughly one tenth to one fifth of the memory you can spare, then adjust after observing peak usage. If your per-chunk code is just a groupby and sum, you can go higher. If it merges or sorts, go lower.
Step 3: Compute the row count
Divide the budget by bytes per row.
import pandas as pd
def pick_chunksize(path, budget_mib, sample_rows=100_000, **read_kwargs):
sample = pd.read_csv(path, nrows=sample_rows, **read_kwargs)
bytes_per_row = sample.memory_usage(deep=True).sum() / len(sample)
rows = int(budget_mib * 1024**2 / bytes_per_row)
return max(rows, 1_000)
size = pick_chunksize(
"big.csv",
budget_mib=200,
usecols=["region", "amount"],
)
print("chunksize:", size)The max(rows, 1_000) floor stops a tiny budget or a very wide file from producing a chunk size so small that overhead dominates. The function returns an integer, which is what chunksize requires.
Then use it:
import pandas as pd
total_rows = 0
for chunk in pd.read_csv("big.csv", usecols=["region", "amount"], chunksize=size):
total_rows += len(chunk)
print(total_rows)This example assumes size was defined by the previous block. Pass the same usecols to both calls so the estimate matches the real read.
Step 4: Verify the peak
An estimate is a starting point. Confirm it by watching the process. On Linux and macOS, the standard library reports peak resident memory:
import resource
import sys
import pandas as pd
total = 0
for chunk in pd.read_csv("big.csv", usecols=["region", "amount"], chunksize=100_000):
total += chunk["amount"].sum()
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
# ru_maxrss is in kilobytes on Linux and in bytes on macOS
divisor = 1024**2 if sys.platform == "darwin" else 1024
print(f"peak memory: {peak / divisor:.0f} MiB")
print(total)The resource module is not available on Windows. There, use a tool such as Task Manager, or the third-party psutil package.
Compare the peak with your budget. If it is far below, you can raise the chunk size and finish faster. If it is near the limit, lower it.
Why the first chunk can mislead you
A sample from the top of a file may not represent the rest. Three things commonly differ:
- String length. Early rows may have short names and later rows long free-text notes. Memory per row grows as you read on.
- Missing values. An integer column with no missing values in the sample becomes
int64. If later chunks contain blanks, the column becomesfloat64, which is the same size but changes behavior. A string column with many blanks storesNaNvalues that cost little. - Sorted data. A file sorted by date or by customer may have a very different mix of values at the end.
If the file is large and heterogeneous, sample more than the head. You can skip rows to read from the middle or end, or measure a few chunks as you go and record the largest.
import pandas as pd
largest = 0.0
with pd.read_csv("big.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
mib = chunk.memory_usage(deep=True).sum() / 1024**2
largest = max(largest, mib)
if i == 9:
break
print(f"largest of first 10 chunks: {largest:.1f} MiB")Breaking out of the with block closes the reader, so the file handle is released.
Speed considerations
Once memory is safe, a few points influence speed:
- Parsing dominates. For plain CSV, most time goes to turning text into numbers and strings. That cost is per byte and does not shrink with a different chunk size. Choosing
usecolsand explicitdtypevalues saves far more time than tuningchunksize. - Per-chunk work should be vectorized. A Python loop over rows inside each chunk (
iterrows,applywith a row function) makes the chunk size nearly irrelevant, since the cost is per row anyway. - Disk caching. Running the same file twice is faster the second time because the operating system caches it. When timing different chunk sizes, run each one more than once, or you will credit the last value with a cache win.
- Output cost. If you write each chunk with
to_csvin append mode, the open and close of the output file happen once per chunk. Very small chunks make that visible.
To compare candidates, time a short run of each on the same sample of the file:
import time
import pandas as pd
for size in (10_000, 50_000, 200_000, 1_000_000):
start = time.perf_counter()
rows = 0
with pd.read_csv("big.csv", usecols=["region", "amount"], chunksize=size) as reader:
for chunk in reader:
rows += len(chunk)
if rows >= 2_000_000:
break
elapsed = time.perf_counter() - start
print(f"{size:>9,} rows/chunk: {elapsed:.2f}s for {rows:,} rows")Each run stops after about two million rows, so you compare like with like. Note that the last chunk of a run may overshoot the target slightly, which is why the printed row count is shown.
Edge cases
- The file has fewer rows than
chunksize. You get one chunk with all the rows. That is fine. - The last chunk is smaller. The final chunk holds whatever remains. Code that assumes every chunk has exactly
chunksizerows will break on it. - Multi-line quoted fields.
chunksizecounts parsed records, not physical lines, so a quoted field containing a newline counts as one row. - Very wide files. With thousands of columns, bytes per row can be large, and a chunk of 100,000 rows may not fit. Let the calculation lower the chunk size, and use
usecols. - Chunk size and results. For correct combinable statistics such as sums and counts, the answer does not depend on the chunk size. If your result changes when you change
chunksize, the computation is not chunk-safe. The pitfalls chapter covers these cases.
Summary table
| Situation | Direction to move | Reason |
|---|---|---|
| Peak memory near the limit | Lower `chunksize` | Smaller chunks and smaller temporary copies |
| Peak memory far below the limit | Raise `chunksize` | Less per-chunk overhead |
| Per-chunk code merges or sorts | Lower `chunksize` | These make large temporary copies |
| Later rows have longer strings than the sample | Lower `chunksize` | Memory per row grows through the file |
| Many tiny appends to an output file | Raise `chunksize` | Fewer file opens and writes |
Exercise
A sample of 50,000 rows measured with memory_usage(deep=True) uses 40 MiB in total. You have decided one chunk may use 256 MiB. Roughly what chunksize should you use, and what should you check afterwards?
Show answer
Bytes per row is about 40 MiB / 50,000, which is 0.0008 MiB, or about 839 bytes. Dividing 256 MiB by that gives about 320,000 rows, so a chunksize near 320,000. Afterwards, measure peak process memory during a real run, because temporary copies made by your per-chunk code and later rows with longer strings can push usage above the estimate. Lower the value if the peak is near your limit.
Exercise
You measure total runtime for chunk sizes 10,000, 100,000 and 1,000,000 and find the times within 15 percent of each other. Which change is most likely to make the job noticeably faster?
Show answer
Reading fewer columns with usecols and giving explicit dtype values. Parsing text dominates the runtime and does not depend on the chunk size, so reducing the amount of data parsed helps more than tuning chunksize.