Sub topic 12
Writing Large Results in Chunks
This chapter assumes you can read and write CSV files with pandas, know what a DataFrame's index and header are, and have run read_csv with its basic arguments. You should also know that to_csv accepts mode, header, and index.
Why chunking matters
A DataFrame lives entirely in memory. A CSV that is larger than your available RAM cannot be loaded with a plain read_csv call, and a transformed copy of it takes even more space. Chunked processing reads and writes the file in pieces, so only one piece is in memory at a time.
Passing chunksize to read_csv changes its return value. Instead of one DataFrame, you get an iterator that yields DataFrames of at most that many rows. You process each one and write it out before the next one is read.
Appending with a header written once
The main difficulty is the output file. If every chunk is written with the default settings, each write would overwrite the previous one, or each appended chunk would repeat the header line. The fix is to write the first chunk in write mode with a header, then append the rest without one.
import pandas as pd
chunks = pd.read_csv("input.csv", chunksize=100_000)
for i, chunk in enumerate(chunks):
chunk.to_csv(
"output.csv",
mode="w" if i == 0 else "a",
header=(i == 0),
index=False,
)The loop uses enumerate to know which chunk it is on. For chunk 0, mode="w" creates or truncates the file and header=True writes the column names. For every later chunk, mode="a" adds rows at the end and header=False skips the column names. Setting index=False keeps the row numbers out of the file.
The diagram below shows the flow for one run.
Transforming each chunk
The loop above copies data unchanged. In practice you change each chunk before writing it. Any operation that works row by row is safe, such as filtering rows, converting types, or adding a computed column.
import pandas as pd
reader = pd.read_csv("input.csv", chunksize=100_000)
for i, chunk in enumerate(reader):
chunk = chunk[chunk["amount"] > 0].copy()
chunk["amount_cents"] = (chunk["amount"] * 100).round().astype("int64")
chunk.to_csv(
"output.csv",
mode="w" if i == 0 else "a",
header=(i == 0),
index=False,
)This example assumes input.csv has a numeric amount column with no missing values after the filter.
Common errors
- Aggregations across chunks give wrong answers. A
groupbyordrop_duplicatesinside the loop only sees one chunk. The same customer in two chunks yields two partial results. Keep a running total in a dictionary, or combine the partial results after the loop. - Dtypes change between chunks.
read_csvguesses types per chunk. A column that looks like integers in one chunk may contain missing values in the next and become float. Passdtype=toread_csvso every chunk uses the same types. - Rerunning appends to old data. Chunk 0 uses
mode="w", so the file is reset on each run. If you start the loop at a different chunk, or delete that logic, you will append to the previous output. - Header repeated in the middle of the file. This happens when
headeris left at its defaultTruefor appended chunks. The column names then appear as a data row partway down.
Exercise
Exercise
You write a loop that calls chunk.to_csv("out.csv", mode="a", index=False) for every chunk, including the first. After a run, you open the file and find the column names repeated many times, and after a second run the file holds twice as many rows. What two changes fix both problems?
Show answer
Use header=(i == 0) so the column names are written only for the first chunk. Use mode="w" if i == 0 else "a" so the first chunk of each run truncates the file and later chunks append to it.