PY-401 ยท pandas basics
Filtering rows
โฑ 9 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก 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.
import pandas as pdorders = pd.DataFrame({"customer": ["Asha", "Ben", "Chen", "Dina", "Eli"],"city": ["Pune", "Leeds", "Pune", "Oslo", "Leeds"],"total": [450, 120, 980, 300, 760],})print(orders[orders["total"] > 400])print(orders[(orders["city"] == "Leeds") & (orders["total"] > 200)])print(orders[orders["city"].isin(["Oslo", "Pune"])]["customer"].tolist())print(orders.query("total < 350").shape[0])
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
customer city total
0 Asha Pune 450
2 Chen Pune 980
4 Eli Leeds 760
customer city total
4 Eli Leeds 760
['Asha', 'Chen', 'Dina']
2 ๐ฏ Set cheap_tea to the rows of menu where the type is "tea" and the price is under 3.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
cheap_tea = menu[(menu["type"] == "tea") & (menu["price"] < 3)]
- The problemSales asks: "Which orders over 400 do we have, and which Leeds customers spent more than 200?" Each question is one filter.
- The Python idea
df[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. - 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") 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.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Missing values โ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"). Writingandraises "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
- Boolean indexing (docs.python.org)