Skip to content
Related Articles

Related Articles

How to Filter Rows Based on Column Values with query function in Pandas?
  • Last Updated : 11 Dec, 2020

In this article, let’s see how to filter rows based on column values. Query function can be used to filter rows based on column values. 

Consider below Dataframe:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import pandas as pd
  
  
data = [['A', 10], ['B', 15], ['C', 14], ['D', 12]] 
df = pd.DataFrame(data, columns = ['Name', 'Age'])
df

chevron_right


Output: 

Our DataFrame 

Now, Suppose You want to get only persons that have Age >13.  We can use Query function of Pandas.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

df.query("Age>13")

chevron_right


Output: 

Using Query with only 1 Column

Now, If you want multiple columns. For example, you want to have Age >13 and Name = C. Then,

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

df.query("Age>13 and Name=='C'")

chevron_right


Output:

Using multiple cols filter


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up