Sub topic 7
Writing results to disk chunk by chunk
This chapter assumes you can read a CSV with read_csv(..., chunksize=...), loop over the chunks, and filter a DataFrame with a boolean mask. You should also know the basics of DataFrame.to_csv.
Why write as you go
The previous chapter collected matching rows from each chunk into a list. That works when the matches are small. If the filter keeps millions of rows, the list grows until memory runs out, which is the problem chunking was meant to avoid.
The fix is to write each filtered chunk to the output file right away and then let it go out of memory. At any moment you hold one input chunk and one filtered chunk.
The append pattern
to_csv has two parameters that make this work:
mode="w"creates the file, or overwrites it if it exists.mode="a"appends to the end of an existing file.headercontrols whether the column names are written. You want them once, at the top of the file.
So the first chunk is written with mode="w" and header=True. Every later chunk is written with mode="a" and header=False.
import pandas as pd
first = True
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
errors = chunk[chunk["status"] == "error"]
errors.to_csv(
"errors.csv",
mode="w" if first else "a",
header=first,
index=False,
)
first = FalseThe first flag does two jobs. It truncates any old errors.csv left from a previous run, and it stops the header from repeating in the middle of the file. Passing index=False keeps the DataFrame's row labels out of the output. Without it, each chunk would write its own index column, and the file would no longer match the input layout.
Why the flag is set after the write
Set first = False after the first to_csv call, not before it. If you set it earlier, the first chunk would be appended instead of written fresh, and a stale file from an earlier run would keep its old rows.
Empty chunks
A chunk can have no matching rows. Writing an empty DataFrame is safe, because to_csv writes only the header (when header=True). This is useful: if nothing matches in the first chunk, the output file still gets its header, and later matches are appended below it. If no chunk matches at all, you end up with a file that contains only the header line.
Transforming before you write
Writing is not limited to filtering. You can also drop columns, rename them, or compute new ones in each chunk before writing. Keep the column order the same in every chunk, because appended rows are matched by position, not by name.
import pandas as pd
first = True
with pd.read_csv("sales.csv", chunksize=200_000) as reader:
for chunk in reader:
chunk["total"] = chunk["price"] * chunk["quantity"]
out = chunk[["order_id", "total"]]
out.to_csv(
"totals.csv",
mode="w" if first else "a",
header=first,
index=False,
)
first = FalseThe code above is the same loop with a different step in the middle. Only the transformation changes. The write logic stays the same.
Common errors
- Repeated headers. You forgot
header=first, so each chunk writes its own header line into the middle of the data. - Overwritten output. You used
mode="w"for every chunk, so the file contains only the last chunk. - Duplicated rows after a rerun. You used
mode="a"for every chunk, so a second run adds to the output of the first. - Extra unnamed column. You left out
index=False, so the index is written as the first column.
Exercise
Exercise
You run a chunked filter that writes out.csv using mode="a" and header=False for every chunk, including the first. What two problems will you see in out.csv, and how do you fix the loop?
Show answer
The file has no header line, and a rerun appends to the previous run's output, so rows are duplicated. Fix it with a flag such as first = True before the loop, use mode="w" if first else "a" and header=first in to_csv, and set first = False after the first write.