How to use the query() function in pandas

The pandas query() function

In pandas, the query() function filters data in a DataFrame. It is used to filter rows in a DataFrame.

Syntax

query(expr,inplace,*kwargs)

Parameters

  • expr: This represents the string to be evaluated.
  • inplace: This is used to determine whether or not we want the entire DataFrame to be modified. The default is False.
  • *kwargs: This represents other optional parameters.

Example

The following code demonstrates how to use the query() function in pandas:

import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
"name": ["Maria","Paul","Eva","Sadia","Joe","Camila"],
"age":[20,22,32,26,29,30],
"salary":[2000,2500,4000,3500,4200,3000],
"gender":["female","male","female","female","male"
,"female"]
})
# Filter rows using query()
print(df.query("age > 22 and gender == 'male'"))

Explanation

  • Line 1: We import the pandas library.

  • Lines 4–10: We create a DataFrame from a dictionary and store the data in the variable, df.

  • Line 13: We filter data in the df using the query() function.

Note: To specify a string value in the query() function, use a single quote.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources