Last updated

Filtering Rows

Definition: Filtering keeps only the rows that meet a condition. You put a True/False test inside the brackets, and Pandas returns the matching rows.

Example 1 — a single condition

import pandas as pd
df = pd.DataFrame({
  "name": ["Sam", "Alex", "Jo", "Pat"],
  "age":  [25, 30, 22, 40]
})
print(df[df["age"] > 24])   # everyone older than 24

Example 2 — combining conditions

Use & for AND and | for OR. Wrap each condition in brackets:

import pandas as pd
df = pd.DataFrame({"name": ["Sam","Alex","Jo","Pat"], "age": [25,30,22,40]})
print(df[(df["age"] > 24) & (df["age"] < 35)])

Example 3 — filter on text

import pandas as pd
df = pd.DataFrame({"name": ["Sam","Alex","Jo"], "city": ["London","Paris","London"]})
print(df[df["city"] == "London"])

💡 Tip: use & and | in Pandas (not the words and/or), and always bracket each condition.

Try it Yourself
Output

          
Ad · responsive