Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

How to use the query() function in pandas

Maria Elijah

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.

RELATED TAGS

pandas
python
RELATED COURSES

View all Courses

Keep Exploring