g↗genai/ learner
Python for AI / Lesson 14

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.

Concept + interactive labBeginner friendly

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:

  1. Comparison condition: Testing a column against a rule such as df["tokens"] > 20 or df["status"] == "ok".
  2. Boolean mask: The pandas Series (a one-dimensional labeled sequence of values) of True and False results returned by a comparison, aligned with the DataFrame's row index.
  3. Row filtering (df[mask]): Passing a boolean mask into df[...] to return a new DataFrame containing only the True rows.
  4. Combined condition ((cond1) & (cond2)): Joining two boolean masks row by row with & (both must be True) 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  timeout

A 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: bool

Notice 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.
Comparing a column against a rule creates a boolean Series aligned with each row's index.
✎ Try it yourselfKnowledge check · Practice only

Quick check: What does a column comparison return?

On our 5-row prompt log df, what does df["tokens"] > 20 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  timeout

Two details are worth noticing right away:

  • Original df is unchanged: df[mask] returns a new filtered DataFrame, so df still holds all 5 rows.
  • Original row index labels stay attached: the kept rows still show index labels 1, 3, and 4 (rather than renumbering to 0, 1, 2), which lets you trace each row back to df.
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.
df[mask] keeps only rows where the mask is True, preserves their original index labels, and leaves df untouched.
✎ Try it yourselfKnowledge check · Practice only

Quick check: Does filtering change the original DataFrame?

After running long_prompts = df[df["tokens"] > 20] on our 5-row df, how many rows are in the original df?

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     ok

Notice 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 Python and: Python's and expects a single True/False value, not a whole Series of booleans, so pandas raises a ValueError.
  • Wrap each comparison in parentheses: In Python, & binds tighter than > and ==. Without parentheses, df["tokens"] > 20 & df["status"] == "ok" tries to evaluate 20 & df["status"] first and raises a TypeError.
Infographic titled Combining masks with &: A row is True only when both masks are True. Two stacked left cards for tokens > 20 (0 False, 1 True, 2 False, 3 True, 4 True) and status == 'ok' (0 True, 1 True, 2 False, 3 True, 4 False) flow right through an & badge into a Combined mask card (0 False, 1 True, 2 False, 3 True, 4 False). Bottom strip reads Syntax rule: Wrap each condition: (cond1) & (cond2).
& compares two boolean masks row by row; parentheses ensure each comparison finishes before & runs.

Quick Questions

Why can't I write df["tokens"] > 20 and df["status"] == "ok"?
Python's and expects one single truth value, not a Series of five booleans, so pandas raises a ValueError. Use & with parentheses instead.
Why do the filtered rows show index 1 and 3 instead of 0 and 1?
pandas preserves each kept row's original index label so you can still tell which rows of df matched your rule.
Does df["tokens"] > 20 include 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")]
✎ Try it yourselfKnowledge check · Practice only

Practice: Which row(s) are in result?

Which row(s) match both df["model"] == "claude" and df["status"] == "timeout"?

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

  1. Keep Show mask (Series) selected and click Condition 1 presets to watch the True/False mask update row by row.
  2. Switch View to Apply df[mask] to see only the True rows kept with their original index labels.
  3. Turn on Combine with & and pick a second condition (try model == "gemini" with status == "timeout" to see an empty 0-row result).
  4. Click Reset to return to the starting view.
Condition 1
Mode
View
mask = df["tokens"] > 20
IndexMaskprompt_idmodeltokensstatus
0Falsep1gemini12ok
1Truep2claude28ok
2Falsep3gpt18timeout
3Truep4gemini35ok
4Truep5claude40timeout

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.

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

Which expression filters df to return a DataFrame of rows where tokens is above 20 AND status is "ok" without raising a Python error?

Take this with you.

Summary Cheat-Sheet

  • Boolean mask: df["tokens"] > 20 tests each row and returns a 1D True/False Series.
  • Filter rows: df[mask] or df[df["tokens"] > 20] keeps only the True rows.
  • 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 are True.
  • Avoid two common errors: Use & (not Python and) 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.