Skip to main content
Albero Academy

Filtering Rows

Keep the rows that match a condition — the heart of pandas.

Selecting & Filtering10 min

Boolean filtering is the heart of pandas — identical in spirit to NumPy masks. Build a condition that yields True/False per row, then index the DataFrame with it to keep the matching rows.

Boolean filtering

conditions select rows
df[df["package"] > 7] # rows where package > 7
# Combine with & (and) | (or) — parenthesise each condition
df[(df["package"] > 6) & (df["programme"] == "Data")]
df[df["programme"].isin(["Data", "Web"])] # membership
df[df["name"].str.startswith("A")] # text condition

The query() alternative

For readability, query() lets you write conditions as a string:

query
df.query("package > 6 and programme == 'Data'")
df.query("package > @threshold") # @ references a Python variable

Key takeaways

  1. 01Filter rows with a boolean condition: df[df["col"] > x].
  2. 02Combine conditions with & and | inside parentheses (not and/or).
  3. 03isin() checks membership; .str methods filter on text.
  4. 04query("...") is a readable string-based alternative.

Finished this chapter?

Mark it complete to track your progress through Pandas.