Boolean Filtering and query()
Filtering means keeping only the rows that satisfy a condition: orders over 100 euros, customers from Spain, readings taken last week. In pandas you write the condition as a comparison on a column, which produces a boolean mask, and use the mask to select rows.
A single condition
import pandas as pd
games = pd.DataFrame({
"title": ["Star Drift", "Cozy Farm", "Pixel Knight", "Deep Sea", "Rally 9", "Moon Base"],
"genre": ["shooter", "sim", "platformer", "sim", "racing", "sim"],
"price": [29.99, 14.99, 9.99, 24.99, 39.99, 19.99],
"rating": [4.1, 4.7, 4.4, 3.8, 3.9, 4.5],
})
mask = games["price"] < 20
print(mask)
print(games[mask])0 False
1 True
2 True
3 False
4 False
5 True
Name: price, dtype: bool
title genre price rating
1 Cozy Farm sim 14.99 4.7
2 Pixel Knight platformer 9.99 4.4
5 Moon Base sim 19.99 4.5
The mask has one True/False per row; games[mask] keeps the rows marked True. Usually you write it inline: games[games["price"] < 20].
Combining conditions
Combine masks with & (and), | (or) and ~ (not). Each condition must be wrapped in parentheses, because these operators bind more tightly than comparisons:
import pandas as pd
games = pd.DataFrame({
"title": ["Star Drift", "Cozy Farm", "Pixel Knight", "Deep Sea", "Rally 9", "Moon Base"],
"genre": ["shooter", "sim", "platformer", "sim", "racing", "sim"],
"price": [29.99, 14.99, 9.99, 24.99, 39.99, 19.99],
"rating": [4.1, 4.7, 4.4, 3.8, 3.9, 4.5],
})
print(games[(games["genre"] == "sim") & (games["rating"] >= 4.5)])
print(games[(games["price"] < 10) | (games["price"] > 35)])
print(games[~(games["genre"] == "sim")]["title"].to_list()) title genre price rating
1 Cozy Farm sim 14.99 4.7
5 Moon Base sim 19.99 4.5
title genre price rating
2 Pixel Knight platformer 9.99 4.4
4 Rally 9 racing 39.99 3.9
['Star Drift', 'Pixel Knight', 'Rally 9']
Note: Python's
and/or/notkeywords do not work on masks.games["price"] < 20 and ...raisesValueError: The truth value of a Series is ambiguous. Always use&,|,~.
Handy mask builders
| Method | Keeps rows where… |
|---|---|
s.isin(["a", "b"]) |
the value is one of a list |
s.between(10, 20) |
the value is in a range (inclusive) |
s.str.contains("text") |
a text value contains a substring |
s.isna() / s.notna() |
the value is / isn't missing |
import pandas as pd
games = pd.DataFrame({
"title": ["Star Drift", "Cozy Farm", "Pixel Knight", "Deep Sea", "Rally 9", "Moon Base"],
"genre": ["shooter", "sim", "platformer", "sim", "racing", "sim"],
"price": [29.99, 14.99, 9.99, 24.99, 39.99, 19.99],
})
print(games[games["genre"].isin(["racing", "shooter"])])
print(games[games["price"].between(15, 25)]["title"].to_list())
print(games[games["title"].str.contains("a", case=False)]["title"].to_list()) title genre price
0 Star Drift shooter 29.99
4 Rally 9 racing 39.99
['Deep Sea', 'Moon Base']
['Star Drift', 'Cozy Farm', 'Deep Sea', 'Rally 9', 'Moon Base']
query(): conditions as a string
query() lets you write the condition as a readable expression. Column names are used directly, and you can use and, or, not and in:
import pandas as pd
games = pd.DataFrame({
"title": ["Star Drift", "Cozy Farm", "Pixel Knight", "Deep Sea", "Rally 9", "Moon Base"],
"genre": ["shooter", "sim", "platformer", "sim", "racing", "sim"],
"price": [29.99, 14.99, 9.99, 24.99, 39.99, 19.99],
"rating": [4.1, 4.7, 4.4, 3.8, 3.9, 4.5],
})
print(games.query("genre == 'sim' and price < 20"))
budget = 25
print(games.query("price <= @budget and rating > 4")["title"].to_list())
print(games.query("genre in ['racing', 'platformer']")["title"].to_list()) title genre price rating
1 Cozy Farm sim 14.99 4.7
5 Moon Base sim 19.99 4.5
['Cozy Farm', 'Pixel Knight', 'Moon Base']
['Pixel Knight', 'Rally 9']
Prefix a Python variable with @ to use it inside the query. Column names with spaces must be wrapped in backticks: query("`unit price` > 5").
Counting and checking
A mask is also useful on its own. Because True counts as 1, sum() counts matching rows and mean() gives the fraction:
import pandas as pd
games = pd.DataFrame({
"genre": ["shooter", "sim", "platformer", "sim", "racing", "sim"],
"rating": [4.1, 4.7, 4.4, 3.8, 3.9, 4.5],
})
good = games["rating"] >= 4.0
print("Games rated 4+:", good.sum())
print(f"Share rated 4+: {good.mean():.0%}")
print("Any below 3?", (games["rating"] < 3).any())
print("All sims rated 3.5+?", (games.loc[games["genre"] == "sim", "rating"] >= 3.5).all())Games rated 4+: 4
Share rated 4+: 67%
Any below 3? False
All sims rated 3.5+? True
Test yourself
Which line keeps rows where age is over 18 AND country is "PT"?
- df[df["age"] > 18 and df["country"] == "PT"]
- df[(df["age"] > 18) & (df["country"] == "PT")]
- df[df["age"] > 18 & df["country"] == "PT"]
- df.filter(age > 18, country = "PT")
Inside df.query(), how do you refer to a Python variable named limit?
- $limit
- @limit
- {limit}
- limit()
What does (df["score"] > 50).mean() return?
- The average score
- The fraction of rows with a score above 50
- The number of rows above 50
- True or False