Filtering DataFrames
Python · 16 questions
Short notes
Key idea
Filtering in pandas means passing a True/False mask to the DataFrame: rows where the mask is True are kept.
Syntax
df[df["amount"] > 1000]
df[(df["city"] == "Chennai") & (df["amount"] > 1000)]
df[(df["status"] == "new") | (df["status"] == "paid")]
df[df["status"].isin(["new", "paid"])]
df[~df["city"].isin(["Chennai"])] # NOT
df[df["name"].str.contains("kumar", case=False)]
df[df["email"].isna()]
df.query("amount > 1000 and city == 'Chennai'")
Example
big_chennai = df[(df["city"] == "Chennai") & (df["amount"] >= 5000)]
print(len(big_chennai))
The inner comparisons each make a column of True/False values. & combines them row by row, and the outer df[...] keeps the rows where both are True. isin is the short way to write many == checks joined with |, and ~ flips a mask, so ~df["city"].isin([...]) means "not in this list". query takes the same conditions as one readable string.
Traps
- Use
&,|,~, notand,or,not. - Wrap each condition in brackets;
&binds tighter than>. == Nonedoesn't find missing values; use.isna()..str.containsfails on NaN; addna=False.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
Which line keeps rows where
ais greater than 1 andbis less than 5? - Question 2easy
Which line finds customers whose city is missing?
- Question 3medium
What does this print?
import pandas as pd df = pd.DataFrame({"city": ["Chennai", None, "Madurai", "Chennai"]}) print(len(df[df["city"] != "Chennai"])) - Question 4hard
What happens when this runs?
import pandas as pd df = pd.DataFrame({"price": [450, 1200, 800], "stock": [0, 5, 0]}) print(len(df[df.price > 500 | df.stock == 0])) - Question 5medium
41 of the 80 orders are delivered. What does this print?
print(len(orders[~(orders["status"] == "delivered")]))
Filtering DataFrames
Filtering DataFrames
Filtering DataFrames
Filtering DataFrames
Filtering DataFrames
11 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.