Sub topic 10
Writing filters with query
This chapter assumes you can build a DataFrame and write boolean masks with &, |, and ~. It uses the same five-city DataFrame as the earlier chapters, rebuilt here so the code runs on its own.
What query does
DataFrame.query takes a string that describes a filter and returns the matching rows. Inside the string, column names act like variables, so you don't repeat the DataFrame name.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)
min_pop = 3000
print(df.query("population_k > @min_pop and continent == 'South America'"))This prints only the Lima row. The @ prefix tells query to read min_pop from your Python code, not look for a column with that name. The equivalent mask version is df[(df["population_k"] > min_pop) & (df["continent"] == "South America")].
query returns a new DataFrame and leaves df unchanged.
Operators you can use
Inside the string you can write and, or, and not, or use &, |, and ~. Comparison chains and membership tests also work, and they read more naturally than their mask forms.
print(df.query("continent in ['Asia', 'Africa']"))
print(df.query("2500 <= population_k <= 5000"))The first call returns Pune and Cairo. The second returns Pune and Quito.
Column names that are not valid identifiers
A name with a space or punctuation can't be written bare. Wrap it in backticks.
renamed = df.rename(columns={"population_k": "population (k)"})
print(renamed.query("`population (k)` > 3000"))Mask or query?
| Situation | Better choice |
|---|---|
| Several conditions that read like a sentence | `query` |
| Filter built from variables with `@` | `query` |
| Method chains where the DataFrame has no name yet | `query` |
| Conditions that call methods such as `.isna()` or `.str` helpers | Mask |
| Column names that are only known at runtime | Mask |
In a method chain, query filters an intermediate result that has no variable name. A mask can't do that without a lambda.
Common errors
- Quoting. The whole filter is a string, so string values inside it need a different quote style. Use
"continent == 'Asia'", not"continent == "Asia"". - Forgetting
@. Writingpopulation_k > min_popmakes pandas look for a column calledmin_pop. It raisesUndefinedVariableError. - Misspelled column names. These raise the same error. Check
df.columnsfirst. - Assuming a view. The result is a new object. If you want to assign into the original rows, use
.locwith a mask, which a later chapter covers.
Exercise
Using a Python variable named limit set to 5000, write a query that returns the cities in South America with a population below limit. Which city is returned?
Show answer
limit = 5000; df.query("continent == 'South America' and population_k < @limit"). It returns Quito, because Lima's population (10092) is above the limit.