Sub topic 12
Writing large results in chunks
This chapter assumes you can read a CSV with read_csv, you know the index, header, and mode arguments of to_csv from earlier chapters, and you have a working idea of what a DataFrame costs in memory. Here you will process a file that is too big to load at once and write the result piece by piece.
Why chunking exists
A DataFrame lives entirely in RAM. A 4 GB CSV can need 8 GB or more once parsed, because pandas stores Python strings as objects and adds per-column overhead. If the file does not fit, read_csv fails with a MemoryError, or the operating system starts swapping and the script crawls.
Chunking trades one big read and one big write for many small ones. You read a fixed number of rows, handle them, write them, and let them go before reading the next batch. Peak memory depends on the chunk size, not on the file size.
The basic pattern
Passing chunksize to read_csv returns an iterator of DataFrames instead of one DataFrame. Each item has up to chunksize rows.
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,
)Three arguments make this work:
mode="w"for the first chunk creates the file, or overwrites an old one.mode="a"for later chunks appends to it.header=(i == 0)writes the column names once. If you leaveheaderat its default, every chunk repeats the header line in the middle of the data.index=Falsekeeps the per-chunk row numbers out of the file. Each chunk restarts its index or carries the original row labels, and neither is useful in the output.
The enumerate counter decides which chunk is first. This is more reliable than checking whether the file exists, because a leftover file from a previous run would silently receive appended rows.
Doing real work on each chunk
Copying data unchanged is rarely the goal. Put the transformation between the read and the write:
import pandas as pd
reader = pd.read_csv(
"input.csv",
chunksize=100_000,
parse_dates=["ordered_at"],
)
for i, chunk in enumerate(reader):
chunk = chunk.dropna(subset=["amount"])
chunk = chunk[chunk["amount"] > 0]
chunk["amount_cents"] = (chunk["amount"] * 100).round().astype("int64")
chunk.to_csv(
"clean.csv",
mode="w" if i == 0 else "a",
header=(i == 0),
index=False,
date_format="%Y-%m-%d",
)All the formatting options from the earlier CSV chapters still apply. Use the same sep, na_rep, float_format, date_format, and encoding for every chunk. If one chunk is written with different options, the file ends up with mixed conventions and no reader can parse it cleanly.
read_csv also works as a context manager, which closes the underlying file handle even if an error interrupts the loop:
import pandas as pd
with pd.read_csv("input.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
chunk.to_csv(
"output.csv",
mode="w" if i == 0 else "a",
header=(i == 0),
index=False,
)How the data flows
Aggregating across chunks
Some results are small even when the input is huge, such as a total per country. You can keep a running result in memory and write it once at the end. The trick is to combine partial results, not to keep raw rows.
import pandas as pd
totals = pd.Series(dtype="float64")
with pd.read_csv("sales.csv", chunksize=200_000) as reader:
for chunk in reader:
partial = chunk.groupby("country")["amount"].sum()
totals = totals.add(partial, fill_value=0)
totals.rename("amount").to_csv("totals_by_country.csv", index_label="country")groupby(...).sum() on each chunk gives a partial total. Series.add(..., fill_value=0) adds two series by label and treats a country missing from one side as zero. After the last chunk, totals holds the true totals, and the single to_csv call writes a small file.
This works for sums and counts. It does not work directly for a mean or a median. For a mean, keep the sum and the count separately and divide at the end. A median has no simple chunk-wise form.
Chunked writing to Parquet and Excel
The append trick belongs to CSV, which is plain text where adding lines at the end is valid. The other formats behave differently.
- Parquet:
to_parquethas no append mode in the pandas API. A Parquet file carries a footer with metadata that is written when the file closes, so you cannot add rows to a finished file. The usual approach is one file per chunk inside a directory. Readers such asread_parquetaccept the directory and combine the files. - Excel: an
.xlsxfile is a zip archive of XML parts. Appending rows to an existing sheet means loading and rewriting the workbook, which is slow and memory heavy. Excel also caps a sheet at 1,048,576 rows, so a result that needs chunking usually does not belong in Excel at all.
A per-chunk Parquet write looks like this:
from pathlib import Path
import pandas as pd
out_dir = Path("clean_parquet")
out_dir.mkdir(exist_ok=True)
with pd.read_csv("input.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
chunk.to_parquet(out_dir / f"part-{i:05d}.parquet", index=False)
combined = pd.read_parquet(out_dir)
print(len(combined))The zero-padded names (part-00000.parquet, part-00001.parquet) sort in write order. Be aware of one risk: read_csv infers dtypes separately for each chunk. A column that holds only whole numbers in one chunk and a missing value in the next becomes int64 in the first file and float64 in the second. The combined read can then fail or upcast. Pass dtype= to read_csv so every chunk gets the same types.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Header line repeated inside the output | `header` left at its default for every chunk | Use `header=(i == 0)` |
| Output has extra rows from an earlier run | First chunk written with `mode="a"` | Use `mode="w"` for the first chunk |
| Unnamed first column in the output | `index=False` missing | Pass `index=False` |
| Column is `int` in some chunks and `float` in others | Per-chunk dtype inference | Pass an explicit `dtype=` to `read_csv` |
| Memory still grows | Chunks collected in a list, or `chunksize` too large | Write each chunk right away. Lower `chunksize` |
| Dates parse as text in some chunks | `parse_dates` not set on the reader | Set `parse_dates` in `read_csv` |
Choosing a chunk size
There is no universal value. Start with 50,000 to 500,000 rows and measure. Very small chunks add overhead from repeated file opens and Python loop iterations. Very large chunks raise peak memory. A useful check is to read one chunk and call chunk.memory_usage(deep=True).sum(), then multiply by the number of chunks you can afford to hold at once, which is normally one, plus working copies made by your transformations.
import pandas as pd
with pd.read_csv("input.csv", chunksize=100_000) as reader:
first = next(iter(reader))
print(f"{first.memory_usage(deep=True).sum() / 1e6:.1f} MB per chunk")Appending also opens the output file again for every chunk. If that cost matters, open the file once and pass the handle:
import pandas as pd
with open("output.csv", "w", newline="", encoding="utf-8") as out:
with pd.read_csv("input.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
chunk.to_csv(out, header=(i == 0), index=False)Here the handle is opened in write mode once, so no mode argument is needed. The newline="" setting stops Python from translating line endings, which avoids doubled carriage returns on Windows.
Verifying a chunked write
A chunked job has more ways to go wrong than a single write, so check the result. Compare row counts, and compare a cheap summary of a key column. Counting rows without loading everything is itself a chunked job:
import pandas as pd
def count_rows(path):
with pd.read_csv(path, chunksize=200_000) as reader:
return sum(len(chunk) for chunk in reader)
expected = count_rows("input.csv")
written = count_rows("output.csv")
print(expected, written)
assert written == expectedIf your transformation filters rows, compare against the expected filtered count instead. For small outputs, pd.testing.assert_frame_equal from the verification chapter is the stronger check.
Exercise
You write a large CSV in chunks with chunk.to_csv("out.csv", mode="a", index=False) for every chunk, including the first. The job runs twice. What two problems appear in out.csv, and how do you fix the code?
Show answer
First, the header is written before every chunk, so column names appear repeatedly inside the data. Second, because the first chunk appends instead of creating the file, the second run adds its rows after those from the first run, so every row is duplicated. Fix it by enumerating the chunks and using mode="w" if i == 0 else "a" together with header=(i == 0).
Exercise
A chunked Parquet job writes one file per chunk. Reading the directory with read_parquet fails because a column is int64 in some files and float64 in others. What causes this, and how do you prevent it?
Show answer
read_csv infers dtypes for each chunk separately. A chunk with no missing values in an integer column gives int64, and a chunk with a missing value gives float64. Prevent it by passing an explicit dtype mapping to read_csv (for example a nullable type such as "Int64") so all chunks share the same schema.