Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.query() function

Pandas df.query() function

Pandas Common Functions Common Pandas functions


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


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

)

print

(

"Original DataFrame:"

)

print

(

df

)

print

(

)

Filter students with scores greater than 85

print

(

"Students with scores greater than 85:"

)

print

(

df.

query

(

'score > 85'

)

)

print

(

)

Filter students whose age equals 18

print

(

"Students whose age equals 18:"

)

print

(

df.

query

(

'age == 18'

)

)

print

(

)

Filter students with grade A

print

(

"Students with grade A:"

)

print

(

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:

  1. Filter conditions are placed in quotes, using SQL-like syntax.
  2. Numeric comparisons use >, ==, < and other operators.
  3. 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

print

(

"Students with scores greater than 85 and age less than 19:"

)

print

(

df.

query

(

'score > 85 and age  90'

)

)

print

(

)

Use a NOT condition: grade is not A

print

(

"Students whose grade is not A:"

)

print

(

df.

query

(

'not grade == "A"'

)

)

print

(

)

A complex compound condition

print

(

"Students aged between 18 and 20 with scores not equal to 88:"

)

print

(

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:

  1. Use and represents the logical AND operation.
  2. Use or represents the logical OR operation.
  3. Use not represents the logical NOT operation.
  4. 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'

print

(

"Filter with a variable - score greater than {}:"

.

format

(

min_score

)

)

print

(

df.

query

(

'score > @min_score'

)

)

print

(

)

print

(

"Filter with a variable - grade is '{}':"

.

format

(

target_grade

)

)

print

(

df.

query

(

'grade == @target_grade'

)

)

print

(

)

Use a list as a variable

target_grades

=

[

'A'

,

'B'

]

print

(

"Students whose grade is in {}:"

.

format

(

target_grades

)

)

print

(

df.

query

(

'grade in @target_grades'

)

)

print

(

)

Use a Python function

def

get_average_score

(

df

)

:

   

return

df

[

'score'

]

.

mean

(

)

print

(

"Students with scores above the average:"

)

print

(

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:

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

print

(

"Students in Beijing:"

)

print

(

df.

query

(

'city == "Beijing"'

)

)

print

(

)

String containment check (using in)

print

(

"Students in Shanghai or Beijing:"

)

print

(

df.

query

(

'city in ["Shanghai", "Beijing"]'

)

)

print

(

)

Use @ to reference a variable containing a string

target_city

=

'Guangzhou'

print

(

"Students in {}:"

.

format

(

target_city

)

)

print

(

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:

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

)

print

(

"Original DataFrame (column names contain spaces):"

)

print

(

df

)

print

(

)

Wrap column names with backticks

print

(

"Students with scores greater than 85:"

)

print

(

df.

query

(

'score > 85'

)

)

print

(

)

print

(

"Students with passing status True:"

)

print

(

df.

query

(

'pass status == True'

)

)

print

(

)

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

}

)

print

(

"Using a reserved word as a column name:"

)

print

(

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:


Notes

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.

Pandas Common Functions Common Pandas functions