Sub topic 2
Reading Less and Processing Results Chunk by Chunk
Assume you know Python loops, context managers, pandas DataFrames, read_csv, and basic groupby operations. This chapter focuses on reducing memory use while filtering, writing, and aggregating a large CSV file.
Reading Less with `usecols` and `dtype`
A large file can use much more memory as a DataFrame than it does on disk. Read only the columns you need with usecols. Set suitable data types with dtype.
import pandas as pd
reader = pd.read_csv(
"events.csv",
usecols=["region", "status", "amount"],
dtype={
"region": "string",
"status": "string",
"amount": "float32",
},
chunksize=100_000,
)
for chunk in reader:
print(chunk.memory_usage(deep=True).sum() / 1024**2, "MiB")memory_usage(deep=True) includes the memory used by Python objects such as strings. Measure a sample before choosing a chunk size and data types. Do not use a narrow integer or floating-point type if the source values can exceed its range.
::: callout note A smaller DataFrame does not always mean a faster job. Very small chunks increase file-reading and Python-loop overhead. Measure both memory use and runtime. :::
Filtering and Collecting Matches
Filter each chunk separately. If the matching rows are expected to be few, collecting them in a list is convenient. The list still grows with the total number of matches, so it can eventually exhaust memory.
matches = []
for chunk in pd.read_csv(
"events.csv",
usecols=["event_id", "status"],
chunksize=100_000,
):
matches.append(chunk[chunk["status"].eq("error")])
errors = pd.concat(matches, ignore_index=True)
print(errors)Writing Results Incrementally
For an unbounded or large result, write each filtered chunk immediately. Write the header only once.
import pandas as pd
first = True
for chunk in pd.read_csv("events.csv", chunksize=100_000):
errors = chunk[chunk["status"].eq("error")]
errors.to_csv(
"errors.csv",
mode="w" if first else "a",
header=first,
index=False,
)
first = FalseAggregating Sums, Counts, and Means
Means cannot be averaged safely by averaging chunk means. Combine sums and counts, then divide once.
import pandas as pd
totals = None
for chunk in pd.read_csv(
"sales.csv",
usecols=["region", "amount"],
dtype={"region": "string", "amount": "float64"},
chunksize=200_000,
):
partial = chunk.groupby("region")["amount"].agg(["sum", "count"])
totals = partial if totals is None else totals.add(partial, fill_value=0)
totals["mean"] = totals["sum"] / totals["count"]
print(totals)The same pattern works for global totals: keep a running sum and count instead of storing every row.
::: exercise Q: Why should a mean be calculated from combined sums and counts rather than from the mean of each chunk? A: Chunks can contain different numbers of rows. Combining sums and counts gives each row the correct weight. :::
::: estimate minutes: 12 :::