Sub topic 6
Filtering Each Chunk and Collecting the Matches
This chapter assumes you can write a for loop and a with block in Python, and that you know how to filter a DataFrame with a boolean mask. It also assumes you have already read a CSV with chunksize. The goal is to keep only the rows you need from a file that is too large to load, and to end up with a result that fits in memory.
The filter-and-collect pattern
A chunked read gives you one DataFrame at a time. Filtering each chunk shrinks it right away, so the memory you use is bounded by the chunk size plus the size of the matches you keep.
The pattern has three steps:
- Read a chunk.
- Apply a boolean mask to keep only the rows you want.
- Store the filtered chunk in a list, then combine the list once at the end.
A worked example
Suppose events.csv has columns timestamp, user_id, status and message, and you want every row where status is "error".
import pandas as pd
matches = []
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
errors = chunk[chunk["status"] == "error"]
matches.append(errors)
result = pd.concat(matches, ignore_index=True)
print(len(result))
print(result.head())Three details matter here:
chunk["status"] == "error"builds a boolean Series. Indexing the chunk with it returns only the rows where the value isTrue.pd.concatis called once, after the loop. Calling it inside the loop copies all earlier data on every pass and gets slower as the result grows.ignore_index=Truegives the result a clean index from 0. Without it, each piece keeps the row labels it had in the original file, so the labels are not contiguous.
Combining several conditions
Use & for and, | for or, and put each condition in parentheses. Python's and and or do not work on Series.
import pandas as pd
matches = []
with pd.read_csv("events.csv", chunksize=100_000, parse_dates=["timestamp"]) as reader:
for chunk in reader:
mask = (chunk["status"] == "error") & (chunk["timestamp"] >= "2026-01-01")
matches.append(chunk.loc[mask])
result = pd.concat(matches, ignore_index=True)For text conditions, chunk["message"].str.contains("timeout", na=False) works the same way. Pass na=False so that missing values count as non-matches instead of breaking the mask.
Guarding against an empty result
If nothing matches, matches holds empty DataFrames, or no DataFrames at all if the file is empty. pd.concat([]) raises ValueError: No objects to concatenate. Check the list first.
import pandas as pd
matches = []
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
errors = chunk[chunk["status"] == "error"]
if not errors.empty:
matches.append(errors)
if matches:
result = pd.concat(matches, ignore_index=True)
else:
result = pd.DataFrame(columns=["timestamp", "user_id", "status", "message"])
print(result.shape)Skipping empty pieces with if not errors.empty also avoids concatenating many zero-row frames, which adds overhead and can affect the result's dtypes.
When the matches are too large
Collecting only works if the filtered result fits in memory. Check this before you start. If the filter keeps 2% of the rows, the result is small. If it keeps 60%, you have the same memory problem again.
You have three options:
- Tighten the filter, or read fewer columns with
usecols. - Reduce each chunk to a summary before you keep it, as the aggregation chapters show.
- Write each filtered chunk to disk instead of keeping it in a list. The next chapter covers this.
Summary
| Step | What to do | Why |
|---|---|---|
| Filter | Apply a boolean mask to each chunk | Shrinks the data before you keep it |
| Collect | Append non-empty results to a list | Appending to a list is cheap |
| Combine | Call `pd.concat` once after the loop | Avoids repeated copying |
| Guard | Check for an empty list | `pd.concat([])` raises an error |
Exercise
A loop reads chunks of 100,000 rows and runs result = pd.concat([result, chunk[chunk["status"] == "error"]]) on every pass. Name two problems with this approach and show the better structure.
Show answer
First, result must already exist, so you need a starting empty DataFrame or a special case for the first chunk. Second, every call copies all rows collected so far, so the loop slows down as the result grows. Better: create matches = [], append each filtered chunk inside the loop (optionally skipping empty ones), and call pd.concat(matches, ignore_index=True) once after the loop, after checking that matches is not empty.
Exercise
You want rows where status is "error" or "warning", and user_id is greater than 1000. Write the mask for a chunk.
Show answer
mask = ((chunk["status"] == "error") | (chunk["status"] == "warning")) & (chunk["userid"] > 1000). Each comparison needs its own parentheses, and the | group needs parentheses so that it is evaluated before &. Alternatively, chunk["status"].isin(["error", "warning"]) & (chunk["userid"] > 1000).