Filtering rows
Use a column comparison to build a True/False boolean mask, pass that mask to df[...] to keep matching rows, and combine conditions with & and parentheses without changing the original DataFrame.
Filtering rows: Keeping only the records that match your rule.
In P1.12 and P1.13, you built DataFrames, inspected table size and columns, and selected one or more columns. Real AI logs often hold thousands of rows, and you usually want only a slice — such as long prompts or timed-out calls.
In pandas, row filtering happens in two clear steps. You will meet these terms in order:
- Comparison condition: Testing a column against a rule such as
df["tokens"] > 20ordf["status"] == "ok". - Boolean mask: The pandas
Series(a one-dimensional labeled sequence of values) ofTrueandFalseresults returned by a comparison, aligned with the DataFrame's row index. - Row filtering (
df[mask]): Passing a boolean mask intodf[...]to return a new DataFrame containing only theTruerows. - Combined condition (
(cond1) & (cond2)): Joining two boolean masks row by row with&(both must beTrue) and parentheses around each comparison.
Every example in this lesson uses the same illustrative 5-row AI prompt log df:
prompt_id model tokens status
0 p1 gemini 12 ok
1 p2 claude 28 ok
2 p3 gpt 18 timeout
3 p4 gemini 35 ok
4 p5 claude 40 timeoutA comparison on a column builds a boolean mask.
Everyday analogy: imagine scanning a 5-line guest list with a pencil and marking Yes or No next to each name before copying anyone onto a new sheet. A column comparison in pandas does that marking step first.
When you write df["tokens"] > 20, pandas checks every value in the tokens column and returns a boolean mask — a 1D Series of True and False values with the same row index:
mask = df["tokens"] > 20
print(mask)0 False
1 True
2 False
3 True
4 True
Name: tokens, dtype: boolNotice that df["tokens"] > 20 does not return the matching rows yet — it only produces the True/False checklist showing which rows pass (rows 1, 3, and 4).
![Infographic titled From column to boolean mask: A comparison tests every row and returns True or False. A tokens column card with Index 0 to 4 and values 12, 28, 18, 35, and 40 flows right through df['tokens'] > 20 into a Boolean mask card with Index 0 to 4 and results False, True, False, True, and True. Bottom strip reads Everyday analogy: Like marking each row on a checklist with Yes or No.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fboolean-mask.3aodyjyig3ufb.webp&w=3840&q=75)
Quick check: What does a column comparison return?
Pass the mask into df[...] to keep only True rows.
Everyday analogy: lay a cutout stencil over a printed sheet so only the open slots show through onto a fresh copy. The original sheet underneath stays intact.
In pandas, pass your boolean mask inside df[...]. You can store the mask in a variable first or write the comparison inline:
# Two-step form
mask = df["tokens"] > 20
long_prompts = df[mask]
# Common one-line form (same result)
long_prompts = df[df["tokens"] > 20]
print(long_prompts) prompt_id model tokens status
1 p2 claude 28 ok
3 p4 gemini 35 ok
4 p5 claude 40 timeoutTwo details are worth noticing right away:
- Original
dfis unchanged:df[mask]returns a new filtered DataFrame, sodfstill holds all 5 rows. - Original row index labels stay attached: the kept rows still show index labels
1,3, and4(rather than renumbering to0, 1, 2), which lets you trace each row back todf.
![Infographic titled Filtering rows with a mask: df[mask] keeps True rows and leaves df unchanged. An Original df card with Index 0 to 4, prompt_id p1 to p5, and Mask False, True, False, True, True flows right through df[mask] into a Filtered DataFrame card with Index 1 p2, 3 p4, and 4 p5. Bottom strip reads Key takeaway: Original df stays 5 rows; kept rows keep index 1, 3, 4.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Frow-filtering.0dwkilmrmgl3y.webp&w=3840&q=75)
Quick check: Does filtering change the original DataFrame?
Combine two conditions with & and parentheses.
Everyday analogy: at an airport gate, a passenger boards only when both checks pass — a valid boarding pass and a matching ID. Each check gives a Yes/No first, and both must be Yes.
To keep rows in df that have more than 20 tokens and status "ok", wrap each comparison in parentheses and join them with &:
ok_long = df[(df["tokens"] > 20) & (df["status"] == "ok")]
print(ok_long) prompt_id model tokens status
1 p2 claude 28 ok
3 p4 gemini 35 okNotice why row 4 (p5) was dropped: its tokens value is 40 (True), but its status is "timeout" (False), so True & False evaluates to False.
Two common syntax mistakes to watch for:
- Use
&, not Pythonand: Python'sandexpects a singleTrue/Falsevalue, not a whole Series of booleans, so pandas raises aValueError. - Wrap each comparison in parentheses: In Python,
&binds tighter than>and==. Without parentheses,df["tokens"] > 20 & df["status"] == "ok"tries to evaluate20 & df["status"]first and raises aTypeError.

Quick Questions
- Why can't I write
df["tokens"] > 20 and df["status"] == "ok"? - Python's
andexpects one single truth value, not a Series of five booleans, so pandas raises aValueError. Use&with parentheses instead. - Why do the filtered rows show index
1and3instead of0and1? - pandas preserves each kept row's original index label so you can still tell which rows of
dfmatched your rule. - Does
df["tokens"] > 20include a row with exactly 20 tokens? - No.
>means strictly greater than 20; use>=when you want to include 20 as well.
Practice: Predict the filtered rows.
Trace both conditions on our 5-row prompt log before running the filter in your head.
# df rows:
# 0: p1 (gemini, 12, ok) 1: p2 (claude, 28, ok)
# 2: p3 (gpt, 18, timeout) 3: p4 (gemini, 35, ok)
# 4: p5 (claude, 40, timeout)
result = df[(df["model"] == "claude") & (df["status"] == "timeout")]Practice: Which row(s) are in result?
Try the Row Filter Lab.
Explore how single and combined boolean masks select rows from our illustrative 5-row prompt log.
Row Filter Lab
Inspect how a comparison builds a True/False mask first, then toggle to df[mask] to see which rows are kept while df stays intact.
Try it in this order
- Keep Show mask (Series) selected and click Condition 1 presets to watch the
True/Falsemask update row by row. - Switch View to Apply df[mask] to see only the
Truerows kept with their original index labels. - Turn on Combine with & and pick a second condition (try
model == "gemini"withstatus == "timeout"to see an empty 0-row result). - Click Reset to return to the starting view.
mask = df["tokens"] > 20| Index | Mask | prompt_id | model | tokens | status |
|---|---|---|---|---|---|
| 0 | False | p1 | gemini | 12 | ok |
| 1 | True | p2 | claude | 28 | ok |
| 2 | False | p3 | gpt | 18 | timeout |
| 3 | True | p4 | gemini | 35 | ok |
| 4 | True | p5 | claude | 40 | timeout |
Boolean mask (Series): 3 True, 2 False · Original df: 5 rows
Toy simulator using the 5-row illustrative prompt log above — not a live Python runtime.
Check your understanding.
Take this with you.
Summary Cheat-Sheet
- Boolean mask:
df["tokens"] > 20tests each row and returns a 1DTrue/FalseSeries. - Filter rows:
df[mask]ordf[df["tokens"] > 20]keeps only theTruerows. - Original table stays intact: Filtering returns a new DataFrame and preserves original row index labels.
- Combine conditions with &: Write
df[(cond1) & (cond2)]so a row is kept only when both masks areTrue. - Avoid two common errors: Use
&(not Pythonand) on Series, and always wrap each comparison in parentheses.
That wraps up Python for AI — you now have the core Python building blocks, safe parsing habits, and pandas table skills to inspect and filter structured AI data.