Pandas df.query() function
query() is a very practical data filtering function in Pandas that allows the use of SQL-like string expressions to filter data. Compared with traditional boolean indexing,query() 's syntax is more concise and intuitive, making it especially suitable for handling complex filtering conditions.
In data analysis work, it is often necessary to filter data according to various conditions.query() The function writes filter conditions as strings, just like writing an SQL query, which is very friendly to users familiar with SQL. At the same time, it also supports the use of Python variables and functions, making dynamic filtering possible.
Basic syntax and parameters
query() is a method of DataFrame, called through the dot operator . It accepts a string argument that contains the filter expression.
Syntax format
DataFrame.query(expr, inplace=False, **kwargs)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| expr | str | Required | The filter expression, similar to an SQL WHERE clause. | - |
| inplace | bool | Optional | Whether to modify the original DataFrame directly. | False |
Return value description
- Return value type: returns a new DataFrame containing the rows that satisfy the filter condition.
- Does not modify the original data: by default, the original DataFrame remains unchanged.
Example
Let us fully master it through a wealth of examples query() through a series of examples from simple to complex.
Example 1: Basic usage - Single-condition filtering
The simplest query() Usage is filtering with a single condition.
Example
import
pandas
as
pd
Create a sample DataFrame
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
,
'Frank'
,
'Grace'
]
,
'age'
:
[
18
,
19
,
17
,
18
,
20
,
19
,
18
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
,
95
,
82
]
,
'grade'
:
[
'A'
,
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original DataFrame:"
)
(
df
)
(
)
Filter students with scores greater than 85
(
"Students with scores greater than 85:"
)
(
df.
query
(
'score > 85'
)
)
(
)
Filter students whose age equals 18
(
"Students whose age equals 18:"
)
(
df.
query
(
'age == 18'
)
)
(
)
Filter students with grade A
(
"Students with grade A:"
)
(
df.
query
(
'grade == "A"'
)
)
Running result:
原始 DataFrame:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
2 Charlie 17 78 B
3 David 18 90 A
4 Eve 20 88 B
5 Frank 19 95 A
6 Grace 18 82 B
Students with scores greater than 85:
name age score grade
1 Bob 19 92 A
3 David 18 90 A
4 Eve 20 88 B
5 Frank 19 95 A
Students whose age equals 18:
name age score grade
0 Alice 18 85 A
3 David 18 90 A
6 Grace 18 82 B
Students with grade A:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
3 David 18 90 A
5 Frank 19 95 A
Code analysis:
- Filter conditions are placed in quotes, using SQL-like syntax.
- Numeric comparisons use
>,==,<and other operators. - String comparisons use double or single quotes.
Example 2: Compound condition filtering
query() supports using logical operators to combine multiple conditions.
Example
import
pandas
as
pd
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
,
'Frank'
,
'Grace'
]
,
'age'
:
[
18
,
19
,
17
,
18
,
20
,
19
,
18
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
,
95
,
82
]
,
'grade'
:
[
'A'
,
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
]
}
df
=
pd.
DataFrame
(
data
)
Use an AND condition: score greater than 85 and age less than 19
(
"Students with scores greater than 85 and age less than 19:"
)
(
df.
query
(
'score > 85 and age 90'
)
)
(
)
Use a NOT condition: grade is not A
(
"Students whose grade is not A:"
)
(
df.
query
(
'not grade == "A"'
)
)
(
)
A complex compound condition
(
"Students aged between 18 and 20 with scores not equal to 88:"
)
(
df.
query
(
'age >= 18 and age <= 20 and score != 88'))
Running result:
Students with a score greater than 85 and age less than 19:
name age score grade
3 David 18 90 A
5 Frank 19 95 A
Students with grade A or score greater than 90:
name age score grade
1 Bob 19 92 A
3 David 18 90 A
5 Frank 19 95 A
Students whose grade is not A:
name age score grade
2 Charlie 17 78 B
4 Eve 20 88 B
6 Grace 18 82 B
Students aged between 18 and 20 whose score is not 88:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
3 David 18 90 A
5 Frank 19 95 A
Code analysis:
- Use
andrepresents the logical AND operation. - Use
orrepresents the logical OR operation. - Use
notrepresents the logical NOT operation. - Compound conditions can be combined arbitrarily to form complex filtering logic.
Example 3: Using Python variables
query() supports the use of Python variables in expressions, which is very useful in dynamic queries.
Example
import
pandas
as
pd
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
,
'Frank'
,
'Grace'
]
,
'age'
:
[
18
,
19
,
17
,
18
,
20
,
19
,
18
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
,
95
,
82
]
,
'grade'
:
[
'A'
,
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
]
}
df
=
pd.
DataFrame
(
data
)
Use the @ symbol to reference Python variables
min_score
=
85
target_grade
=
'A'
(
"Filter with a variable - score greater than {}:"
.
format
(
min_score
)
)
(
df.
query
(
'score > @min_score'
)
)
(
)
(
"Filter with a variable - grade is '{}':"
.
format
(
target_grade
)
)
(
df.
query
(
'grade == @target_grade'
)
)
(
)
Use a list as a variable
target_grades
=
[
'A'
,
'B'
]
(
"Students whose grade is in {}:"
.
format
(
target_grades
)
)
(
df.
query
(
'grade in @target_grades'
)
)
(
)
Use a Python function
def
get_average_score
(
df
)
:
return
df
[
'score'
]
.
mean
(
)
(
"Students with scores above the average:"
)
(
df.
query
(
'score > @get_average_score(df)'
)
)
Running result:
使用变量筛选 - 分数大于 85:
name age score grade
1 Bob 19 92 A
3 David 18 90 A
4 Eve 20 88 B
5 Frank 19 95 A
使用变量筛选 - 等级为 'A':
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
3 David 18 90 A
5 Frank 19 95 A
Students whose grade is in ['A', 'B']:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
2 Charlie 17 78 B
3 David 18 90 A
4 Eve 20 88 B
5 Frank 19 95 A
6 Grace 18 82 B
Students whose scores are above average:
name age score grade
1 Bob 19 92 A
3 David 18 90 A
5 Frank 19 95 A
Code analysis:
- Use
@The symbol can reference Python variables in query expressions. - You can directly use a Python list for
inchecks. - You can call Python functions to compute dynamic thresholds.
Example 4: String operations
query() also supports some common string operations.
Example
import
pandas
as
pd
Create a DataFrame with string columns
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
,
'Frank'
,
'Grace'
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Beijing'
,
'Guangzhou'
,
'Shanghai'
,
'Beijing'
,
'Shenzhen'
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
,
95
,
82
]
}
df
=
pd.
DataFrame
(
data
)
Filter records for a specific city
(
"Students in Beijing:"
)
(
df.
query
(
'city == "Beijing"'
)
)
(
)
String containment check (using in)
(
"Students in Shanghai or Beijing:"
)
(
df.
query
(
'city in ["Shanghai", "Beijing"]'
)
)
(
)
Use @ to reference a variable containing a string
target_city
=
'Guangzhou'
(
"Students in {}:"
.
format
(
target_city
)
)
(
df.
query
(
'city == @target_city'
)
)
Running result:
Students in Beijing:
name city score
0 Alice Beijing 85
2 Charlie Beijing 78
5 Frank Beijing 95
Students in Shanghai or Beijing:
name city score
0 Alice Beijing 85
1 Bob Shanghai 92
2 Charlie Beijing 78
4 Eve Shanghai 88
5 Frank Beijing 95
Students in Guangzhou:
name city score
3 David Guangzhou 90
Code analysis:
query()supports equality comparison of strings.- You can use the
inThe keyword checks whether an element is in a list. - You can use the
@references a string variable.
Example 5: Handling column names with spaces or special characters
If a column name contains spaces or special characters, you can use backticks ` to wrap the column name.
Example
import
pandas
as
pd
Create a DataFrame with column names containing spaces
data
=
{
'student name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
]
,
'pass status'
:
[
True
,
True
,
False
,
True
,
True
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original DataFrame (column names contain spaces):"
)
(
df
)
(
)
Wrap column names with backticks
(
"Students with scores greater than 85:"
)
(
df.
query
(
'score > 85'
)
)
(
)
(
"Students with passing status True:"
)
(
df.
query
(
'pass status == True'
)
)
(
)
You can also use this method to handle reserved words as column names
df2
=
pd.
DataFrame
(
{
'class'
:
[
'A'
,
'B'
,
'A'
,
'B'
,
'A'
]
,
'def'
:
[
1
,
2
,
3
,
4
,
5
]
def is a Python reserved word
}
)
(
"Using a reserved word as a column name:"
)
(
df2.
query
(
'def > 3'
)
)
Running result:
原始 DataFrame(列名包含空格):
student name score pass status
0 Alice 85 True
1 Bob 92 True
2 Charlie 78 False
3 David 90 True
4 Eve 88 True
Students with scores greater than 85:
student name score pass status
1 Bob 92 True
3 David 90 True
4 Eve 88 True
Students whose status is True:
student name score pass status
0 Alice 85 True
1 Bob 92 True
3 David 90 True
4 Eve 88 True
Using reserved words as column names:
class def
3 B 4
4 A 5
Code analysis:
- By using backticks, you can handle column names that contain spaces or conflict with Python reserved words.
scoreandpass statusis used to reference column names.defdemonstrates how to handle Python reserved words as column names.
Notes
query()Column names in expressions must be valid Python identifiers, or wrapped in backticks.- String comparisons can use single or double quotes.
- Use
@The symbol references Python variables. - For large DataFrames,
query()its performance is usually better than traditional boolean indexing. - If the filter expression contains reserved words or special characters, backticks must be used.
Tip:
query()is especially suitable for scenarios that require dynamically building filter conditions, such as filtering data based on user input or configuration files. Combined with Python's string formatting capabilities, very flexible data queries can be achieved.
Summary
query() is a powerful data filtering function in Pandas that provides SQL-like query syntax, making complex conditional filtering more concise and readable.
Its main advantages include: concise and intuitive syntax, support for compound logical operations, support for Python variables and functions, and the ability to handle special column names. In real data analysis, especially when filter conditions need to be built dynamically,query() is a very practical tool.
Common Pandas functions