Pandas drop rows by condition – Python Pandas : How to Drop rows in DataFrame by conditions on column values

How to Drop rows in DataFrame by conditions on column values in Python ?

Pandas drop rows by condition: In this article we will discuss how we can delete rows in a dataframe by certain conditions on column values.

DataFrame provides a member function drop() which is used to drop specified labels from rows or columns in dataframe.

DataFrame.drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)

Let’s try with an example:

#Program :

import pandas as pd
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
   ('anjali',28,'agra','dog','lily'),
   ('tia',42,'jaipur','elephant','lotus'),
   ('kapil',51,'patna','cow','tulip'),
   ('raj',30,'banglore','lion','orchid')]

#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
print(df)
Output:
     Name  Age     Place       Animal       Flower
a    riya     37       delhi           cat             rose
b  anjali    28       agra           dog             lily
c     tia      42       jaipur     elephant        lotus
d   kapil    51      patna          cow           tulip
e     raj      30     banglore      lion          orchid

Delete rows based on condition on a column

Drop rows pandas condition: Let’s try with an example by deleting a row:

deleteRow = df[df['Place'] == 'patna'].index
df.drop(deleteRow, inplace=True)
print(df)
Output:
 Name    Age     Place      Animal       Flower
a    riya    37     delhi           cat            rose
b  anjali   28      agra          dog            lily
c     tia     42      jaipur     elephant      lotus
e     raj     30    banglore      lion         orchid

Here, we give the condition i.e

df[‘Place’] == ‘patna’

Internally if we will see it is giving series object with True and False.

a   False
b   False
c   False
d   True
e   False

Name: Place, dtype: bool

Delete rows based on multiple conditions on a column :

Dataframe drop rows by condition: Let’s try with multiple conditions

deleteRow = df[(df['Age'] >= 30) & (df['Age'] <= 40)].index
df.drop(deleteRow, inplace=True)
print(df)
Output:
    Name  Age     Place     Animal      Flower
b  anjali   28       agra        dog          lily 
c     tia     42       jaipur    elephant    lotus

Here, we join two conditions i.e df[‘Age’]>=30 and df[‘Age’]<=40 by putting ’&’ between two conditions.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Remove Contents from a Dataframe