Sub topic 3
Reading a CSV in chunks with chunksize
This chapter assumes you know basic Python loops and context managers, and that you have used pandas read_csv and DataFrames. You will learn how chunksize changes what read_csv returns and how to loop over the result.
What chunksize changes
Normally pd.read_csv parses the whole file and returns one DataFrame. When you pass chunksize=N, it 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 and gives you a DataFrame. The final chunk may have fewer than N rows.
Only one chunk needs to be in memory at a time, so peak memory depends on the chunk size and not on the file size.
A first example
This loop counts the rows in a file without ever loading all of 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)Each chunk is an ordinary DataFrame with up to 100,000 rows. You can use any DataFrame method on it. When the next iteration starts, the previous chunk is released as soon as nothing refers to it.
Things that stay the same, and things that change
Each chunk is parsed on its own, but the reader remembers the header, so every chunk has the correct column names. The index is different. By default it continues across chunks, so the second chunk with 100,000 rows starts at index 100,000. Row labels stay unique across the file.
Column dtypes are inferred per chunk. That can produce different types for the same column in different chunks. A later chapter covers this problem. For now, remember that a chunk is a sample of the file, not the whole file.
Controlling the reader with get_chunk
The reader also has a get_chunk method. It lets you advance by hand, and it accepts a different row count for one call. Close the reader when you finish.
import pandas as pd
reader = pd.read_csv("big.csv", chunksize=50_000)
first_chunk = reader.get_chunk()
next_chunk = reader.get_chunk(1_000)
reader.close()Here first_chunk has up to 50,000 rows and next_chunk has the following 1,000 rows. This is useful for peeking at the start of a file or for reading a header block of a different size.
Closing matters because the reader holds the file open. In a loop, the safest form is a with block, which closes the reader even if an exception occurs.
import pandas as pd
with pd.read_csv("big.csv", chunksize=100_000) as reader:
for chunk in reader:
print(chunk.shape)Common errors
- Treating the result as a DataFrame.
pd.read_csv("big.csv", chunksize=1000).head()fails because the reader has noheadmethod. Iterate over it or callget_chunk()first. - Iterating twice. A reader is consumed as you go. A second
forloop over the same reader yields nothing. Create a new reader if you need another pass. - Keeping every chunk. Appending all chunks to a list and calling
pd.concatat the end rebuilds the full file in memory, which defeats the purpose. Reduce or write each chunk inside the loop instead. - Expecting a global result from one chunk. Statistics such as a median or a distinct count cannot be read from a single chunk.
Summary of the pattern
- Open the file with
chunksizeinside awithblock. - Loop over the reader.
- Reduce each chunk to something small, or write it out.
- Combine the small results after the loop.
Exercise
A colleague runs reader = pd.read_csv("big.csv", chunksize=10_000), loops over it once to count rows, then loops again to sum a column, and gets 0 for the sum. Why, and how do you fix it?
Show answer
The reader is an iterator and the first loop consumed it, so the second loop has no rows to process. Fix it by creating a new reader with another pd.read_csv("big.csv", chunksize=10_000) call for the second pass, or by doing both the count and the sum in the same loop.
Exercise
What do you get from pd.read_csv("big.csv", chunksize=500), and what is the index of the first row in the second chunk?
Show answer
You get a reader (an iterator of DataFrames), not a DataFrame. The index continues across chunks by default, so the first row of the second chunk has index 500.