Change language

Python | Filtering data with the Pandas .query () method

|

Analyzing data requires a lot of filtering operations. Pandas provide many methods for filtering a data frame, and Dataframe.query() is one of them.

Syntax: DataFrame.query(expr, inplace = False, ** kwargs)

Parameters:
expr: Expression in string form to filter data.
inplace: Make changes in the original data frame if True
kwargs: Other keyword arguments.

Return type: Filtered Data frame

To download the used CSV file, click here.

Note. Dataframe.query () only works if the column name no spaces. Therefore, before applying the method, spaces in column names are replaced with "_"

Example # 1: Filtering one condition

This example filters data based on one condition ... Before using the query () method, spaces in column names were replaced with & # 39; _ & # 39 ;.

# import pandas package

import pandas as pd

 
# create data frame from CSV file

data = pd.read_csv ( "employees.csv" )

 
# replace spaces with & # 39; _ & # 39;

data.columns = [column. replace ( "" , "_" ) for column in data.columns]

 
# filtering by query method

data.query ( ’Senior_Management == True’ , inplace = True )

 
# display
data

Output:
As shown in the output image, there are now only those in the data lines where senior control is True. 

Example # 2: filtering multiple conditions

In this example, the dataframe has been filtered by several conditions. Before using the query () method, spaces in column names were replaced with & # 39; _ & # 39 ;.

# import pandas package

import pandas as pd

 
# create data frame from CSV file

data = pd.read_csv ( "employees.csv" )

 
# replace spaces with & # 39; _ & # 39;

data.columns = [column. replace ( "" , "_" ) for column in data.columns]

 
# filtering by query method

data.query (’Senior_Management = = True  

and Gender = = "Male" and Team = = " Marketing " 

  and First_Name = = "Johnny" ’, inplace = True )

 
# display
data

Output:
As shown in the output image, only two rows were returned based on the filters applied. 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method