How to drop a specific row in a dataframe with pandas ?

Published: September 02, 2021

Tags: Python; Pandas; DataFrame;

DMCA.com Protection Status

Examples of how to remove a given row in a dataframe with pandas in python:

Drop a given row (Example 1)

Let's create a dataframe with pandas:

import pandas as pd
import numpy as np

data = np.random.randint(5, size=(4,3))

df = pd.DataFrame(data=data,columns=['C1','C2','C3'])

returns for example:

   C1  C2  C3
0   3   3   1
1   0   2   4
2   0   4   4
3   4   2   0

To drop the row with index = 2 for example, a solution is to use drop() (Note that 0 means axis=0 here since drop() can also be used to remove columns):

df.drop([2], 0, inplace=True)

returns then:

   C1  C2  C3
0   3   3   1
1   0   2   4
3   4   2   0

Note: drop can also be used to remove multiple rows. For example, to remove row 0 and 2:

df.drop([0,2], 0,  inplace=True)

returns

   C1  C2  C3
1   0   2   4
3   4   2   0

Drop a given row (Example 2)

Another example:

import pandas as pd
import numpy as np

data = np.random.randint(5, size=(4,3))

df = pd.DataFrame(data=data,columns=['C1','C2','C3'], index=['A','B','C','D'])

wiith a dataframe with index = ['A','B','C','D']

   C1  C2  C3
A   3   3   1
B   0   2   4
C   0   4   4
D   4   2   0

To remove the row with index = B:

df.drop(['B'],0, inplace=True)

returns

   C1  C2  C3
A   3   3   1
C   0   4   4
D   4   2   0

Drop rows where a condition is true

Another useful example is to remove rows where a condition is true

import pandas as pd
import numpy as np

data = np.random.randint(5, size=(4,3))

df = pd.DataFrame(data=data,columns=['C1','C2','C3'])

returns

   C1  C2  C3
0   3   3   1
1   0   2   4
2   0   4   4
3   4   2   0

Let's assume we want to remove rows where column C1 = 0. To do that, let's first find the indexes where the condition is true:

index_list = df.index[ df.loc[:,'C1'] == 0]

print(index_list)

returns:

Int64Index([1, 2], dtype='int64')

The we can use drop() to remove rows:

df.drop(index_list,0, inplace=True)

returns here:

   C1  C2  C3
0   3   3   1
    3   4   2   0

References