Sub topic 3
Reading a CSV in chunks with chunksize
This chapter assumes you know basic Python (loops and with blocks), pandas DataFrames and read_csv, and simple groupby aggregation. Earlier chapters explained why a big file can exhaust memory and how to measure a DataFrame's size. Here you learn the core tool for working around that limit: the chunksize parameter of pd.read_csv.
What chunksize changes
Normally pd.read_csv("big.csv") parses the whole file and returns one DataFrame. If you pass chunksize=N, pandas returns a reader object instead. The reader is an iterator. Each time you ask it for the next item, it parses the next N rows from the file and gives you a DataFrame with those rows.
The reader is of type TextFileReader. You rarely need that name, but it helps to know that the object you get back is not a DataFrame. Code like df.head() or df["amount"] fails on it.
import pandas as pd
total_rows = 0
for chunk in pd.read_csv("big.csv", chunksize=100_000):
total_rows += len(chunk)
print(total_rows)Only one chunk is held by the loop at a time. When the loop moves on, the previous chunk has no more references and Python can free it.
A runnable example
The examples in this tutorial use files you may not have. The snippet below creates a small file so you can run everything and see exact output. It writes 250 rows and reads them 100 at a time.
import pandas as pd
pd.DataFrame(
{"id": range(250), "value": [i * 0.5 for i in range(250)]}
).to_csv("sample.csv", index=False)
for i, chunk in enumerate(pd.read_csv("sample.csv", chunksize=100)):
print(i, len(chunk), chunk.index[0], chunk.index[-1])The output is:
0 100 0 99
1 100 100 199
2 50 200 249Four details follow from this output.
- Every chunk has at most 100 rows. The last chunk holds whatever is left, so it can be smaller.
- Every chunk is a normal DataFrame with the file's column names. pandas reads the header line once and reuses it for each chunk.
- The index keeps counting across chunks. The second chunk starts at 100, not 0. If you want a per-chunk index, call
chunk.reset_index(drop=True). - Concatenating all chunks gives the same rows you would get from a plain
read_csv. Chunking changes how the file is delivered, not what it contains.
chunksize counts rows, not bytes
chunksize is a number of rows. The memory a chunk needs is rows times the cost of one row, and the cost of one row depends on how many columns you have and what types they are. A chunk of 100,000 rows with three numeric columns is a few megabytes. A chunk of 100,000 rows with 40 text columns can be hundreds of megabytes, because Python string objects are expensive.
So the same chunksize can be safe for one file and too large for another. Measure a sample instead of guessing. This is the technique from the previous chapter:
import pandas as pd
chunk = pd.read_csv("big.csv", nrows=100_000)
print(chunk.memory_usage(deep=True).sum() / 1024**2, "MiB")
print(chunk.dtypes)If one 100,000-row chunk takes 80 MiB, you have a rough budget. Peak memory during processing is higher than the chunk alone, because parsing builds temporary data and your own code creates filtered copies and intermediate results. A common rule is to keep the chunk well under a quarter of the memory you can spare. A later chapter covers choosing a size in detail.
Lazy reading and single use
The reader does not parse the file when you create it. It opens the file and reads the header, and it parses data rows only when you ask for the next chunk. This has two consequences.
First, errors in the data can appear late. If row 7,000,000 has a malformed line, your loop runs for a long time and then fails on the chunk that contains it. Test your logic on nrows= first, and see the on_bad_lines option if your data is messy.
Second, the reader is a one-pass iterator. Once the loop finishes, the reader is exhausted and has no rows left to give. Looping over the same reader again yields nothing, with no error. If you need a second pass, call pd.read_csv again to make a new reader.
import pandas as pd
reader = pd.read_csv("sample.csv", chunksize=100)
first_pass = sum(len(c) for c in reader)
second_pass = sum(len(c) for c in reader)
print(first_pass, second_pass)This prints 250 0. The second pass finds nothing.
Closing the reader
The reader holds an open file handle. A for loop that runs to the end does not necessarily close it promptly, and a loop that exits early with break or an exception leaves the file open until the object is garbage collected. Since pandas 1.2 the reader works as a context manager, so a with block closes it for you:
import pandas as pd
with pd.read_csv("sample.csv", chunksize=100) as reader:
for chunk in reader:
print(len(chunk))Use this form for anything you will keep in a script. The next chapter covers the other ways to drive a reader, including calling next() and get_chunk().
Per-chunk settings versus whole-file settings
Most read_csv parameters still work with chunksize, and they apply to the whole file, not to each chunk. A few combinations behave in ways you should know about.
| Parameter | Behavior with chunksize |
|---|---|
| `usecols` | Applied to every chunk. Only the listed columns are parsed, which lowers memory per chunk. |
| `dtype` | Applied to every chunk. Setting it explicitly keeps types the same across chunks. |
| `nrows` | Limits the total rows read across all chunks, not rows per chunk. |
| `skiprows` | Skips rows at the start of the file, before the first chunk is built. |
| `index_col` | Applied to every chunk. Each chunk gets its own index from that column. |
| `parse_dates` | Applied to every chunk. Parsing happens chunk by chunk. |
The nrows case surprises people. chunksize=100_000, nrows=250_000 gives chunks of 100,000, 100,000 and 50,000 rows, then stops. It is a convenient way to test a pipeline on the start of a big file.
Type inference happens per chunk
When you do not give dtype, pandas infers each column's type from the data it parses. With chunking, that inference is done separately for each chunk. A column that looks like integers in the first chunk might contain a stray value such as "N/A" or "unknown" in the 40th chunk. That chunk then holds the column as object, and code that worked on earlier chunks, such as a sum, can fail or give different results.
An integer column can also become float in a chunk that contains missing values. Chunks can therefore disagree about types even when the file is valid.
You avoid this by stating the types you expect:
import pandas as pd
dtypes = {"id": "int64", "value": "float64"}
for chunk in pd.read_csv("sample.csv", chunksize=100, dtype=dtypes):
assert chunk["value"].dtype == "float64"With an explicit dtype, a bad value raises an error at the chunk where it appears. That error is usually better than a silent type change. A later chapter returns to this under pitfalls.
Accidental full loads
The most common mistake with chunksize is to undo its benefit. These patterns put the whole file into memory anyway:
import pandas as pd
# Builds a list of every chunk, then concatenates them.
df = pd.concat(pd.read_csv("big.csv", chunksize=100_000))
# Same effect with an explicit list.
chunks = []
for chunk in pd.read_csv("big.csv", chunksize=100_000):
chunks.append(chunk)
df = pd.concat(chunks)Both versions hold all rows at once, and concat also needs extra room to build the combined frame, so the peak can exceed a plain read_csv. Only collect chunks when each one has been reduced first, for example after filtering to the few rows you need. The filtering chapter covers that safely.
Checking your understanding of the model
A useful mental model has three parts. The reader is a cursor over the file. Each step moves the cursor forward by up to chunksize rows and gives you those rows as a DataFrame. Anything you want to survive beyond a step must be stored by your own code, outside the chunk.
Counting rows, as in the first example, is the simplest case. You keep one integer. The aggregation chapters extend this idea to sums, means and grouped totals, where you keep a small table of partial results and update it for every chunk.
Exercise
A script runs reader = pd.read_csv("data.csv", chunksize=50_000), then computes total = sum(len(c) for c in reader) and later computes valid = sum(c["amount"].notna().sum() for c in reader). The second result is always 0, although the file has many valid amounts. What is wrong, and how do you fix it?
Show answer
The reader is a one-pass iterator, and the first line of code consumed it completely, so the second loop finds no chunks. Fix it by creating a new reader for the second pass, for example with pd.read_csv("data.csv", chunksize=50_000) as reader:, or by computing both numbers in one loop over a single reader.
Exercise
You call pd.read_csv("big.csv", chunksize=200_000, nrows=500_000). How many chunks do you get, and how many rows are in each?
Show answer
Three chunks, with 200,000, 200,000 and 100,000 rows. nrows limits the total rows read across the whole file, and chunksize sets the size of each chunk within that limit, so the last chunk is the remainder.