Drop or delete the row in python pandas with conditions

In this tutorial we will learn how to drop or delete the row in python pandas by index, delete row by condition in python pandas and delete the row in python pandas  by position. Lets see example of each.

Create Dataframe:

import numpy as np

#Create a DataFrame
d = {
    'Name':['Alisa','Bobby','jodha','jack','raghu','Cathrine',
            'Alisa','Bobby','kumar','Alisa','Alex','Cathrine'],
    'Age':[26,24,23,22,23,24,26,24,22,23,24,24],
     
       'Score':[85,63,55,74,31,77,85,63,42,62,89,77]}

df = pd.DataFrame(d,columns=['Name','Age','Score'])
df

the dataframe will be

Drop or delete rows with conditions in python pandas 1

 

Simply drop a row or observation:


# Drop an observation or row
df.drop([1,2])

The above code will drop the second and third row. So the resultant dataframe will be

Drop or delete rows with conditions in python pandas 2

 

Drop a row or observation by condition:

we can drop a row when it satisfies a specific condition


# Drop a row by condition
df[df.Name != 'Alisa']

The above code takes up all the names except Alisa, thereby dropping the row with name ‘Alisa’. So the resultant dataframe will be

Drop or delete rows with conditions in python pandas 3

 

Drop a row or observation by index:

We can drop a row by index as shown below


# Drop a row by index
df.drop(df.index[2])

The above code drops the row with index number 2. So the resultant dataframe will be

Drop or delete rows with conditions in python pandas 4

 

Drop the row by position:

Now let’s drop the bottom 3 rows of a dataframe as shown below


# Drop bottom 3 rows
df[:-3]

The above code selects all the rows except bottom 3 rows, there by dropping bottom 3 rows, so the resultant dataframe will be

Drop or delete rows with conditions in python pandas 5

 

previous-small Drop or delete rows with conditions in python pandas                                                                                                                next_small Drop or delete rows with conditions in python pandas