Sub topic 13
Reading large CSV files in chunks
This chapter assumes you can use read_csv with usecols and dtype, and that you know what a DataFrame is. Here you will process a file that is too big to load at once.
Why read in chunks
read_csv normally parses the whole file into one DataFrame. A file larger than your free memory makes that call fail or slow your machine to a crawl.
Passing chunksize=N changes the return value. You get an iterator that yields DataFrames of up to N rows each. Only one chunk is held in memory at a time, so memory use depends on N and not on the file size.
Aggregating chunk by chunk
The example first writes a 250,000-row file so that you can run it as shown. It then totals amount per region without loading the whole file.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
pd.DataFrame(
{
"region": rng.choice(["north", "south", "east"], 250_000),
"amount": rng.integers(1, 100, 250_000),
}
).to_csv("big.csv", index=False)
totals = pd.Series(dtype="float64")
with pd.read_csv(
"big.csv",
chunksize=100_000,
usecols=["region", "amount"],
dtype={"region": "string"},
) as reader:
for chunk in reader:
partial = chunk.groupby("region")["amount"].sum()
totals = totals.add(partial, fill_value=0)
print(totals.astype("int64"))Three points about this code:
- The
withblock closes the file when the loop ends, even if an error interrupts it. usecolsanddtypestill apply, and they reduce memory further. Use them together withchunksize.totals.add(partial, fill_value=0)handles a region that appears in one chunk but not another.
Combining partial results correctly
Each chunk must produce something that can be merged with the other chunks' results. Sums, counts, minimums and maximums merge easily. Other statistics do not.
| Goal | Per chunk, keep | Final step |
|---|---|---|
| Total | the chunk's sum | add the sums |
| Mean | the chunk's sum and row count | total sum divided by total count |
| Maximum | the chunk's maximum | maximum of the maximums |
| Median | not possible this way | use a different tool |
Averaging the chunk means is wrong when chunks have different sizes. The last chunk is usually smaller than the others.
To keep only some rows, filter each chunk and collect the survivors:
import pandas as pd
pieces = []
for chunk in pd.read_csv("big.csv", chunksize=100_000):
pieces.append(chunk[chunk["amount"] > 95])
big_sales = pd.concat(pieces, ignore_index=True)
print(len(big_sales))This works only if the filtered result fits in memory. Concatenating every unfiltered chunk gives you the original memory problem back.
Common errors
- Treating the return value as a DataFrame. With
chunksize,df.head()ordf["amount"]fails because you hold an iterator. Loop over it first. - Reusing the iterator. An iterator is exhausted after one pass. To loop again, call
read_csvagain. - Types that change between chunks. Inference runs per chunk, so a column of integers can become floats in a chunk that contains a missing value. Set
dtypeexplicitly so every chunk matches. - Choosing a poor chunk size. Very small chunks add loop overhead. Very large ones use too much memory. Start with 100,000 rows and adjust after checking memory use.
Exercise
A file has 1,000,000 rows, and you read it with chunksize=300_000. You want the mean of the "amount" column. Why is it wrong to average the four chunk means, and what should you keep from each chunk instead?
Show answer
The last chunk has only 100,000 rows, so a simple average of the four chunk means gives it the same weight as the 300,000-row chunks. Keep each chunk's sum and row count (chunk["amount"].sum() and chunk["amount"].count()). After the loop, divide the total of the sums by the total of the counts.