Sub topic 6
Filtering Each Chunk and Collecting the Matches
This chapter assumes you can write a loop over pd.read_csv(..., chunksize=...), use a with block on the reader, and filter a DataFrame with a boolean mask. Here you will use those pieces to pull a small subset out of a file that is too large to load whole.
The idea: shrink each chunk before you keep it
Filtering is the simplest use of chunked reading. Each chunk is a normal DataFrame, so you apply the filter you would apply to a full file. You keep only the rows that match and discard the rest before reading the next chunk.
Memory use then stays near the size of one chunk plus the matches collected so far. This works well when the matches are much smaller than the file. If you keep 1% of 40 GB, the result is about 400 MB and fits in memory. If you keep 60%, it does not. The next chapter covers that case by writing matches to disk.
A complete, runnable example
The script below creates a small test file, so you can run it as shown. It then reads the file in chunks of 1,000 rows and keeps the rows where status is "error".
import numpy as np
import pandas as pd
# Build a sample file: 10,000 rows, about 5% errors.
rng = np.random.default_rng(0)
pd.DataFrame(
{
"id": np.arange(10_000),
"status": rng.choice(["ok", "error"], size=10_000, p=[0.95, 0.05]),
"latency_ms": rng.integers(1, 2_000, size=10_000),
}
).to_csv("events.csv", index=False)
matches = []
with pd.read_csv("events.csv", chunksize=1_000) as reader:
for chunk in reader:
matches.append(chunk[chunk["status"] == "error"])
result = pd.concat(matches, ignore_index=True)
print(len(result))
print(result.head())Three details matter here.
chunk[mask]returns a new DataFrame holding copies of the matching rows. Once the loop moves on, the original chunk can be freed. Only the small filtered pieces stay alive inmatches.pd.concatruns once, after the loop. Each call toconcatcopies all of its inputs. Calling it inside the loop, as inresult = pd.concat([result, hits]), copies the growing result on every iteration. The total work grows quadratically with the number of chunks.ignore_index=Truegives the result a fresh index from 0. Without it, the index repeats the row numbers within each chunk. Row 0 of every chunk would be labelled 0 in the combined frame.
Index labels and row order
read_csv numbers rows continuously across chunks. The second chunk of 1,000 rows starts at index 1000, not 0. So if you want to keep the original row position, leave ignore_index off. The index of the combined result will then be each match's row number in the file, assuming the file has no custom index_col.
Chunks arrive in file order, and the list preserves that order. The concatenated result therefore lists matches in the same order as the file.
Filters that behave differently in chunks
Most filters give the same answer whether you apply them to the whole file or to chunks. Row-wise conditions work this way: each row is judged on its own values. Some filters need care.
Row-wise filters (safe)
Comparisons, isin, string tests and date ranges all depend only on the row itself.
import pandas as pd
wanted_regions = {"EU", "APAC"}
matches = []
with pd.read_csv(
"sales.csv",
usecols=["order_id", "region", "amount", "note", "order_date"],
parse_dates=["order_date"],
chunksize=200_000,
) as reader:
for chunk in reader:
mask = (
chunk["region"].isin(wanted_regions)
& (chunk["amount"] >= 1_000)
& (chunk["order_date"] >= "2026-01-01")
& chunk["note"].str.contains("refund", case=False, na=False)
)
matches.append(chunk[mask])
result = pd.concat(matches, ignore_index=True) if matches else pd.DataFrame()
print(result.shape)Points to notice:
- Combine conditions with
&,|and~, and wrap each comparison in parentheses. Python'sandandordo not work on Series. str.containsreturnsNaNfor missing text. Using that as a mask raises an error.na=Falsetreats missing values as non-matches.usecolsandparse_datesshrink and prepare each chunk before your filter runs. Reading only the columns you need cuts memory per chunk and speeds up parsing.
Filters that look at other rows (unsafe)
Some conditions compare a row against the whole dataset. Examples are "the top 1% by amount", "amount above the column mean", and "drop duplicate id values". Inside a chunk, "the mean" is the mean of that chunk only, so the result differs from the full-file answer.
There are two ways to handle this:
- Compute the dataset-wide value first with a separate pass over the file, then filter in a second pass.
- Keep a per-chunk candidate set, then apply the global rule to the collected candidates.
For example, to find the 10 largest amounts overall, keep the 10 largest from each chunk. The overall top 10 must be among those candidates, so the final answer is exact.
import pandas as pd
candidates = []
with pd.read_csv("sales.csv", usecols=["order_id", "amount"], chunksize=200_000) as reader:
for chunk in reader:
candidates.append(chunk.nlargest(10, "amount"))
top10 = pd.concat(candidates, ignore_index=True).nlargest(10, "amount")
print(top10)Deduplication needs the same two-stage approach. drop_duplicates() inside each chunk removes duplicates within that chunk only. Duplicates that span chunks survive. Run drop_duplicates again on the concatenated result, which works if the deduplicated set fits in memory.
Stopping early
If you need only the first N matches, stop reading once you have them. Leaving the with block closes the file.
import pandas as pd
LIMIT = 500
matches = []
found = 0
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
hits = chunk[chunk["status"] == "error"]
matches.append(hits)
found += len(hits)
if found >= LIMIT:
break
first_matches = pd.concat(matches, ignore_index=True).head(LIMIT)
print(len(first_matches))The last chunk may push found past the limit, so head(LIMIT) trims the surplus. Because chunks arrive in file order, the result holds the first LIMIT matches in the file.
Guarding against a result that is too big
A filter that matches more rows than you expected can use all your memory, which is the failure you were avoiding. If you cannot be sure how selective the filter is, add a guard that stops the loop with a clear error.
import pandas as pd
MAX_MATCHES = 5_000_000
matches = []
kept = 0
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
hits = chunk[chunk["status"] == "error"]
kept += len(hits)
if kept > MAX_MATCHES:
raise RuntimeError(
f"More than {MAX_MATCHES:,} matches; write them to disk instead."
)
matches.append(hits)Pick the limit from a measurement: memory_usage(deep=True) on a sample of matches, divided by its row count, gives bytes per row. Multiply by the limit to estimate memory use.
Empty matches and `concat`
Two situations leave you with an empty list or empty frames.
- If no chunk produced any rows,
matchesis still a list of empty DataFrames, andpd.concatworks. The result has the right columns and zero rows. - If the file has only a header, the reader may yield no chunks at all. Then
matchesis an empty list, andpd.concat([])raisesValueError: No objects to concatenate.
Guard the second case by building an empty frame with the correct columns.
import pandas as pd
matches = []
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
matches.append(chunk[chunk["status"] == "error"])
if matches:
result = pd.concat(matches, ignore_index=True)
else:
result = pd.read_csv("events.csv", nrows=0) # header only, correct columnsDtype drift when combining chunks
Pandas infers column types separately for each chunk. A column that looks numeric in one chunk can contain a stray text value in another, so the pieces end up with different dtypes. A column of IDs may be int64 in most chunks, but float64 in a chunk with a missing value, or object in a chunk with a bad entry. concat then upcasts the whole column to the widest type. An integer ID column silently becomes floats, or text.
Fix this by declaring types up front so that every chunk is parsed the same way.
import pandas as pd
dtypes = {"id": "int64", "status": "category", "latency_ms": "int32"}
with pd.read_csv("events.csv", dtype=dtypes, chunksize=100_000) as reader:
result = pd.concat(
(chunk[chunk["status"] == "error"] for chunk in reader),
ignore_index=True,
)
print(result.dtypes)Here a generator expression feeds concat directly. Because concat consumes it lazily into a list, the memory behaviour matches the explicit loop.
A category column adds one more wrinkle. If the chunks carry different sets of categories, concat falls back to object for that column. When the category set is known, pass pd.CategoricalDtype(categories=[...]) in dtype so all chunks share it.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `result = pd.concat([result, hits])` inside the loop | Quadratic copying, slow on many chunks | Append to a list, concat once |
| Forgetting `ignore_index=True` | Repeated index labels | Pass `ignore_index=True`, or keep the labels on purpose |
| Filtering on a global statistic inside a chunk | Wrong answer, no error | Two passes, or per-chunk candidates plus a final step |
| Not guarding against large results | Out-of-memory crash late in the run | Count matches and stop at a limit |
| Leaving dtypes to inference | Columns change type between chunks | Pass `dtype` and `parse_dates` |
| Using `pd.concat([])` with no chunks | `ValueError` | Check the list, fall back to an empty frame |
Exercises
Exercise
A script collects error rows with result = pd.concat([result, hits]) inside the chunk loop, and it slows down as the file grows. Why does it slow down, and what is the fix?
Show answer
Each concat copies the whole accumulated result plus the new rows, so the total work grows quadratically with the number of chunks. Append each filtered chunk to a list inside the loop and call pd.concat(list, ignore_index=True) once after the loop.
Exercise
You want every row whose amount is above the overall column mean, from a file read in chunks. Why does chunk[chunk["amount"] > chunk["amount"].mean()] give the wrong answer, and how would you get the right one?
Show answer
Inside a chunk, mean() is the mean of that chunk only, so each chunk uses a different threshold. Make a first pass that accumulates the total sum and count to get the global mean, then make a second pass that filters every chunk with that single value.