query()
functionIn pandas, the query()
function filters data in a DataFrame. It is used to filter rows in a DataFrame.
query(expr,inplace,*kwargs)
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.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'"))
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
CONTRIBUTOR
View all Courses