TECHNOLOGIESTieInn Technologies

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 &, |, ~, not and, or, not.
  • Wrap each condition in brackets; & binds tighter than >.
  • == None doesn't find missing values; use .isna().
  • .str.contains fails on NaN; add na=False.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Filtering DataFrames

  1. Question 1easy

    Which line keeps rows where a is greater than 1 and b is less than 5?

  2. Filtering DataFrames

  3. Question 2easy

    Which line finds customers whose city is missing?

  4. Filtering DataFrames

  5. Question 3medium

    What does this print?

    import pandas as pd
    
    df = pd.DataFrame({"city": ["Chennai", None, "Madurai", "Chennai"]})
    print(len(df[df["city"] != "Chennai"]))
  6. Filtering DataFrames

  7. 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]))
  8. Filtering DataFrames

  9. Question 5medium

    41 of the 80 orders are delivered. What does this print?

    print(len(orders[~(orders["status"] == "delivered")]))

11 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.