How to use dataframe.query() method In Python Pandas

The query() method takes up the expression that returns a boolean value, processes all the rows in the Dataframe, and returns the resultant Dataframe with selected rows. 

Example 1: Pandas select rows by Dataframe.query() method based on column values 

Select  rows where the name=”Albert”

Python3




df.query('name=="Albert"')


Output

 

Example 2: Select rows based on iple column conditions

This example is to demonstrate that logical operators like AND/OR can be used to check multiple conditions. we are trying to select rows where points>50 and the player is not Albert.

Python3




df.query('points>50 & name!="Albert"')


Output

 

How to select rows from a dataframe based on column values ?

In this article, we will cover how we select rows from a DataFrame based on column values in Python

The rows of a Dataframe can be selected based on conditions as we do use the SQL queries. The various methods to achieve this is explained in this article with examples. 

Similar Reads

Importing Dataset for demonstration

To explain the method a dataset has been created which contains data of points scored by 10 people in various games. The dataset is loaded into the Dataframe and visualized first. Ten people with unique player id(Pid) have played different games with different game id(game_id) and the points scored in each game are added as an entry to the table. Some of the player’s points are not recorded and thus NaN value appears in the table....

Method 1: Boolean Indexing method

...

Method 2: Positional indexing method

In this method, for a specified column condition, each row is checked for true/false. The rows which yield True will be considered for the output. This can be achieved in various ways. The query used is Select rows where the column Pid=’p01′...

Method 3: Using dataframe.query() method

...

Method 3: Using isin() method

...

Method 4: Using Numpy.where() method

...

Method 5: Comparison with other methods

The methods loc() and iloc() can be used for slicing the Dataframes in Python. Among the differences between loc() and iloc(), the important thing to be noted is iloc() takes only integer indices, while loc() can take up boolean indices also....