Sub topic 10
Writing filters with query
This chapter assumes you can build a DataFrame from a dictionary and that you know boolean masks, including &, |, ~, isin, and between. If those are unfamiliar, review the earlier chapters on masks first. Here you will write the same filters as strings with DataFrame.query, learn where that style helps, and learn where it breaks.
The idea: a filter as a string
A boolean mask repeats the DataFrame name for every condition. query takes the filter as one string and looks up column names for you.
This chapter uses the same city table as before.
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"],
)
# Mask version
print(df[(df["population_k"] > 3000) & (df["continent"] == "South America")])
# query version
print(df.query("population_k > 3000 and continent == 'South America'"))Both calls return the same single row, Lima. The query version has no repeated df[...] and no parentheses around each comparison.
query returns a new DataFrame and leaves df unchanged. It filters rows only. It cannot select columns or assign values.
How query evaluates the string
pandas parses the string and resolves each name it finds. A name is looked up in the column names first, then in the index. Names that start with @ are looked up as Python variables in the calling scope. The result must be a boolean array, which pandas uses as a row mask.
Operators you can use
Inside the string you can write conditions in either style.
| Meaning | Keyword style | Symbol style | Column |
|---|---|---|---|
| and | `a > 1 and b < 5` | `(a > 1) & (b < 5)` | |
| or | `a > 1 or b < 5` | `(a > 1) \ | (b < 5)` |
| not | `not (a > 1)` | `~(a > 1)` |
The keyword style is the usual choice because it needs no extra parentheses. The comparison operators ==, !=, <, <=, >, and >= work as in Python.
Two shortcuts replace helpers from the mask chapters:
# Chained comparison replaces between()
print(df.query("2500 <= population_k <= 5000"))
# in and not in replace isin()
print(df.query("continent in ['Asia', 'Africa']"))
print(df.query("continent not in ['Europe']"))The first call returns Pune and Quito. The second returns Pune and Cairo. The third returns every city except Oslo.
Unlike between, a chained comparison lets you choose which ends are inclusive. Use < instead of <= to exclude an end.
Using Python variables with @
Prefix a variable with @ to read it from the surrounding code.
min_pop = 3000
wanted = ["Asia", "Africa"]
target = "Peru"
print(df.query("population_k > @min_pop and continent in @wanted"))
print(df.query("country == @target"))The first call returns Pune and Cairo. The second returns Lima.
Leaving off the @ is the most common error. Without it, pandas looks for a column or index level with that name and fails:
min_pop = 3000
try:
df.query("population_k > min_pop")
except pd.errors.UndefinedVariableError as err:
print(err) # name 'min_pop' is not definedIf a column and a variable share a name, the bare name means the column and @name means the variable. Using @ removes the ambiguity.
Column names that are not plain identifiers
A column name with spaces or punctuation cannot be written bare. Wrap it in backticks.
spaced = df.rename(columns={"population_k": "population k"})
print(spaced.query("`population k` > 3000"))Column names that collide with Python keywords, such as a column named class, also need backticks.
Filtering on the index
The name index refers to the row labels when the index has no name. When the index has a name, use that name.
print(df.query("index in ['a', 'c']"))
by_city = df.set_index("city")
print(by_city.query("city in ['Lima', 'Oslo']"))The first call returns rows a and c. The second returns Oslo and Lima, because set_index made the city names the index and named it city.
String methods and missing values
Method calls such as .str.startswith and .notna() are not supported by every evaluation engine. The default engine may use numexpr when it is installed, and it cannot evaluate method calls. Pass engine="python" to use plain Python evaluation:
print(df.query("city.str.startswith('Q')", engine="python"))
scores = pd.DataFrame({"name": ["x", "y", "z"], "score": [1.0, None, 3.0]})
print(scores.query("score.notna()", engine="python"))
print(scores.query("score.isna()", engine="python"))The first call returns Quito. The next two return rows x and z, then row y.
As with masks, score == None does not find missing values. A missing number is NaN, and NaN == NaN is false. Use notna() and isna().
When a filter needs several string methods or custom logic, a mask is often easier to read and test. Compare the two styles:
mask = df["city"].str.contains("i") & df["population_k"].between(1000, 5000)
print(df[mask])Writing back: query cannot assign
query returns a filtered copy, so assigning to its result does not change df. To assign, compute the mask with DataFrame.eval, which accepts the same expression syntax and returns a boolean Series. Then use .loc:
mask = df.eval("population_k > 3000 and continent == 'South America'")
df.loc[mask, "population_k"] = 10100
print(df.loc[mask])If you plan to add columns to a query result, call .copy() on it first. This follows the rule from the assignment chapter: make the independent subset explicit.
large = df.query("population_k > 3000").copy()
large["rank"] = large["population_k"].rank(ascending=False)When to choose query
| Situation | Better choice |
|---|---|
| Several simple column comparisons | `query` |
| Thresholds held in variables | `query` with `@` |
| Conditions mixing many method calls | Mask |
| Filter result used for assignment | Mask, or `eval` plus `.loc` |
| Condition built from a list of dynamic clauses | Mask, combined with `&` in a loop |
| Very large frame with `numexpr` installed | `query`, which may be faster; measure first |
On small frames, speed is not a reason to pick either style. Choose the one that reads better.
Common errors
- Missing
@on a variable raisesUndefinedVariableError. - Using a method call without
engine="python"can raiseNotImplementedErroror a similar error, depending on your engine setup. - Comparing text without quotes makes pandas treat the word as a name. In
continent == Asia,Asiais read as a column. Quote strings inside the query, using single quotes inside a double-quoted Python string. - Mixing
andwith&without parentheses leads to precedence mistakes. Pick one style per query. - Passing untrusted text straight into a query string is unsafe. The string is evaluated as an expression, so user input can run unintended code. Pass such values through
@variables instead.
Exercise
Using the city DataFrame, write one query call that returns cities with a population over 2,000 thousand that are not in Africa. Use a variable for the threshold and the keyword not in for the continent test.
Show answer
threshold = 2000 followed by df.query("population_k > @threshold and continent not in ['Africa']") returns Lima, Pune, and Quito. Oslo is excluded by the population test (709) and Cairo by the continent test.
Exercise
You run scores.query("score != None") to drop missing scores, but every row is returned. Why does this fail, and what is the fix?
Show answer
A missing score is NaN, and comparisons with NaN or None do not detect it, so the filter keeps every row. Use scores.query("score.notna()", engine="python"), or the mask scores[scores["score"].notna()].