Sub topic 13
Reading large CSV files in chunks
This chapter assumes you can already call read_csv with usecols and dtype, and that you know what a DataFrame and a groupby are. You will learn how to process a CSV file that is too large to load at once. The approach is to read it in pieces and combine the results.
Why a file can be too big
read_csv normally parses the whole file into one DataFrame. The DataFrame often needs more memory than the file takes on disk. Text columns are stored as Python objects, and numbers default to 64-bit types. A 2 GB CSV can need 4 GB or more of RAM, and parsing needs extra working memory on top of that.
Try the cheap fixes first, because they sometimes remove the need for chunks:
- Read only the columns you need with
usecols. - Use smaller types, such as
int32,float32orcategory, throughdtype. - Read a sample with
nrowsto check the layout before committing to a full load.
If the data still does not fit, or you only need an aggregate or a filtered subset, read the file in chunks.
The chunksize pattern
When you pass chunksize=N, read_csv does not return a DataFrame. It returns a reader, an iterator that yields DataFrames of up to N rows each. Only one chunk is held in memory at a time, plus whatever you keep.
To follow along, first create a test file with 250,000 rows.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 250_000
pd.DataFrame({
"region": rng.choice(["north", "south", "east", "west"], size=n),
"amount": rng.integers(1, 500, size=n),
}).to_csv("big.csv", index=False)Now compute a total and a row count without ever holding the whole file.
import pandas as pd
total = 0
rows = 0
with pd.read_csv("big.csv", chunksize=100_000, usecols=["amount"]) as reader:
for chunk in reader:
total += chunk["amount"].sum()
rows += len(chunk)
print(rows, total)The with block closes the underlying file when the loop ends, even if an exception occurs. Readers support this since pandas 1.2. Each chunk is an ordinary DataFrame, so every method you know works on it.
Choosing a chunk size
chunksize counts rows, not bytes. The memory per chunk depends on how many columns you read and on their types. A reasonable starting point is between 50,000 and 1,000,000 rows. Measure a single chunk to tune it:
import pandas as pd
with pd.read_csv("big.csv", chunksize=100_000) as reader:
first = next(reader)
print(first.memory_usage(deep=True).sum() / 1e6, "MB")Very small chunks slow the job down because of per-chunk overhead. Very large chunks defeat the purpose. The final chunk is usually shorter than the others, so do not assume every chunk has exactly N rows.
Combining results across chunks
The main design problem is that most statistics cannot be computed by averaging the per-chunk answers. You need to keep partial results that can be merged exactly.
| Statistic | What to keep from each chunk | How to combine |
|---|---|---|
| Sum, count, min, max | The value itself | Sum, sum, min of mins, max of maxes |
| Mean | Sum and count | Total sum divided by total count |
| Group totals | A per-group sum and count | Concatenate, then group again and sum |
| Distinct values | A set or the unique values | Union of the sets |
| Median, quantiles | Not decomposable | Use a sample, a histogram or a different tool |
Groups are the usual trap. Rows for one region are spread across many chunks, so grouping inside a chunk gives only a partial answer. Concatenate the partial tables and group a second time.
import pandas as pd
partials = []
with pd.read_csv("big.csv", chunksize=100_000, dtype={"amount": "int32"}) as reader:
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 partial table has one row per region, so the list stays tiny however large the file is.
Filtering while reading
If you need only a subset of rows, filter each chunk and keep the survivors. Then join them once at the end.
import pandas as pd
with pd.read_csv("big.csv", chunksize=100_000) as reader:
big_sales = pd.concat(
(chunk[chunk["amount"] > 490] for chunk in reader),
ignore_index=True,
)
print(big_sales.shape)Call pd.concat once on the whole collection. Appending to a DataFrame inside the loop copies the data on every iteration and is slow. Also check that the filtered result fits in memory. If the filter keeps most of the rows, you have only postponed the problem.
Writing out as you go
When the result is itself large, write each processed chunk to disk instead of collecting it. Write the header only for the first chunk.
import pandas as pd
with pd.read_csv("big.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
cleaned = chunk[chunk["amount"] > 0]
cleaned.to_csv("cleaned.csv", mode="w" if i == 0 else "a",
header=(i == 0), index=False)Pulling chunks on demand
If you want chunks one at a time rather than in a for loop, use iterator=True and call get_chunk.
import pandas as pd
with pd.read_csv("big.csv", iterator=True) as reader:
head = reader.get_chunk(5)
more = reader.get_chunk(3)
print(head.index.tolist(), more.index.tolist())The reader remembers its position, so the second call continues where the first stopped. The printed indexes are [0, 1, 2, 3, 4] and [5, 6, 7].
Gotchas
Types are inferred per chunk
Without an explicit dtype, pandas infers each column's type separately for every chunk. A column that looks numeric at the top of the file can contain text further down. Chunk one then holds integers and chunk two holds strings, and concatenating or comparing them can fail or silently produce object columns.
import pandas as pd
from io import StringIO
text = "code\n1\n2\nA\nB\n"
for chunk in pd.read_csv(StringIO(text), chunksize=2):
print(chunk["code"].dtype)
for chunk in pd.read_csv(StringIO(text), chunksize=2, dtype={"code": "string"}):
print(chunk["code"].dtype)The first loop prints int64 and then object. The second prints string both times. For any file you process in chunks, declare the types of columns you rely on.
The index keeps counting
The row index continues across chunks, so the second chunk starts at 100000 when chunksize is 100,000. This is usually what you want, because it matches the row position in the file. Pass ignore_index=True to concat if you want a fresh 0-based index.
The header is read once
read_csv consumes the header line once and applies the column names to every chunk. Do not skip rows or reapply names per chunk. Options such as parse_dates, na_values and decimal also apply to every chunk, so the settings you learned for whole-file reads carry over unchanged.
`low_memory` is not chunking
The low_memory parameter (default True for the C engine) makes pandas parse the file internally in blocks to save memory during parsing. It does not limit the size of the DataFrame you get back. It can also cause the mixed-type warning described above. Setting dtype is the correct fix for that warning, not low_memory=False.
Order and state
Chunks arrive in file order, so running totals and "previous row" logic work, but you must carry the last row of a chunk forward yourself if a calculation spans a chunk boundary. Chunking also does not help with operations that need all rows at once, such as a global sort. For those, consider a database, Parquet files or a library built for larger-than-memory data.
Choosing an approach
- Use
usecolsanddtypefirst. They are the simplest change and often enough. - Use chunks with a running aggregate when you need totals, counts, means or grouped summaries.
- Use chunks with a filter when you need a subset that is much smaller than the file.
- Use chunks with incremental writing when you are transforming the file and the output is large.
- Switch tools when you need global operations such as sorting, joins on huge tables or exact medians.
Exercise
You process a 10 GB sales file with chunksize=500_000 and want the average amount for each region. A teammate suggests computing chunk.groupby("region")["amount"].mean() in each chunk and then averaging those results. Why is this wrong, and what should you keep from each chunk instead?
Show answer
Averaging per-chunk means gives each chunk equal weight even though chunks can contain different numbers of rows for a region, and the last chunk is usually smaller. The result is biased. Keep the per-region sum and count from each chunk with .agg(["sum", "count"]), concatenate the partial tables, group by region again and add them up, then divide the total sum by the total count.
Exercise
A column account_id holds values like 00123. When you read the file in chunks, some chunks show the column as int64 and others as object, and the leading zeros are lost in some. What argument fixes this, and why does the problem happen only with chunked reads?
Show answer
Pass dtype={"account_id": "string"} (or str) to read_csv. Without it, pandas infers the type separately for each chunk, so a chunk with only digit-like values becomes integer, which drops the leading zeros, while a chunk with a non-numeric value becomes object. An explicit dtype makes every chunk use the same type.