Lesson 10 of 23
โฎPrev Nextโฏ

PY-401 ยท pandas basics

Filtering rows

โฑ 9 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

10of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    You filter a DataFrame by putting a condition in square brackets: orders[orders["total"] > 400] keeps only the rows where it is True. Combine conditions with & and |, each in brackets, use .isin([...]) to match a list of values, and df.query("total < 350") when you prefer to write the rule as text. It is the same boolean mask idea as in NumPy, applied to whole rows.

    • Filter rows with one condition
    • Combine conditions with & and |
    • Match a list with isin, or use query

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Filtering rows, running
    1. import pandas as pd
    2. orders = pd.DataFrame({
    3. "customer": ["Asha", "Ben", "Chen", "Dina", "Eli"],
    4. "city": ["Pune", "Leeds", "Pune", "Oslo", "Leeds"],
    5. "total": [450, 120, 980, 300, 760],
    6. })
    7. print(orders[orders["total"] > 400])
    8. print(orders[(orders["city"] == "Leeds") & (orders["total"] > 200)])
    9. print(orders[orders["city"].isin(["Oslo", "Pune"])]["customer"].tolist())
    10. print(orders.query("total < 350").shape[0])
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemSales asks: "Which orders over 400 do we have, and which Leeds customers spent more than 200?" Each question is one filter.
    2. The Python ideadf[df["col"] > 10]You filter a DataFrame by putting a condition in square brackets: orders[orders["total"] > 400] keeps only the rows where it is True.
    3. In real lifeAn online shop sends a "your cart is waiting" email only to carts[(carts["items"] > 0) & (carts["hours_idle"] > 24)], the shoppers who left something behind a day ago.

    Start with a question

    Sales asks: "Which orders over 400 do we have, and which Leeds customers spent more than 200?" Each question is one filter.

    Most business questions are filters: this region, this month, orders above a limit. pandas makes each one a single line.

    Explain it like I'm 10

    Filtering is a sieve. You pour all the rows in, and only the ones that match your rule stay in the sieve.

    The technical explanation

    orders["total"] > 400 is a True/False Series, one value per row. Putting it in orders[...] keeps the True rows.

    The kept rows keep their original index labels, which is why you see 0, 2, 4 in the output. .reset_index(drop=True) renumbers them.

    df["city"].isin(["Oslo", "Pune"]) is True when the city is any of the listed values.

    df.query("total < 350 and city == 'Leeds'") writes the same filter as a string, which can be easier to read.

    Syntax

    df[df["col"] > 10]
    df[(df["a"] > 1) & (df["b"] == "x")]
    df[df["col"].isin(["x", "y"])]
    df.query("col < 10")

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    An online shop sends a "your cart is waiting" email only to carts[(carts["items"] > 0) & (carts["hours_idle"] > 24)], the shoppers who left something behind a day ago.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What does df[df["age"] > 30] return?
    2. 2. Which means "city is Leeds AND total over 200"?
    3. 3. Which keeps rows where city is Oslo or Pune?
    4. 4. After filtering, why is the index 0, 2, 4?
    5. 5. df.query("total < 350") is the same asโ€ฆ

    Questions people ask

    How do I filter a pandas DataFrame by multiple conditions?

    Wrap each condition in brackets and join them with & for and, | for or, and ~ for not, for example df[(df.city == "Leeds") & (df.total > 200)].

    What does "The truth value of a Series is ambiguous" mean?

    You used and, or or if with a whole column. Python needs one True or False, but a column has many. Use & and | between bracketed conditions, or .any() and .all() when you really want one answer.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner How do I filter a pandas DataFrame by multiple conditions?

    Wrap each condition in brackets and join them with & for and, | for or, and ~ for not, for example df[(df.city == "Leeds") & (df.total > 200)].

    beginner What does "The truth value of a Series is ambiguous" mean?

    You used and, or or if with a whole column. Python needs one True or False, but a column has many. Use & and | between bracketed conditions, or .any() and .all() when you really want one answer.

    intermediate What does df[df["age"] > 30] return?

    Rows where age is over 30. A boolean Series inside the brackets keeps the matching rows.

    intermediate Which means "city is Leeds AND total over 200"?

    (df.city == "Leeds") & (df.total > 200). Use & with brackets around each condition.

    Quick revision

    Remember

    • Filter rows with one condition
    • Combine conditions with & and |
    • Match a list with isin, or use query
    • Use & and | with brackets: (df.a > 1) & (df.b == "x"). Writing and raises "The truth value of a Series is ambiguous".

    Syntax

    df[df["col"] > 10]
    df[(df["a"] > 1) & (df["b"] == "x")]
    df[df["col"].isin(["x", "y"])]
    df.query("col < 10")

    Official documentation