Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to drop Ith row of a data frame

How do I drop row number i of a DF ?

I did the thing below but it is not working.

 DF = DF.drop(i) 

So I wonder what I miss there.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You must pass a label to drop. Here drop tries to use i as a label and fails (ith KeyError) as your index probably has other values. Worse, if the index was composed of integers in random order you might drop an incorrect row without noticing it.

Use:

df.drop(df.index[i])

Example:

df = pd.DataFrame({'col': range(4)}, index=list('ABCD'))
out = df.drop(df.index[2])

output:

   col
A    0
B    1
D    3

pitfall

In case of duplicated indices, you might remove unwanted rows!

df = pd.DataFrame({'col': range(4)}, index=list('ABAD'))
out = df.drop(df.index[2])

output (A is incorrectly dropped!):

   col
B    1
D    3

workaround:

import numpy as np

out = df[np.arange(len(df)) != i]

drop several indices by position:

import numpy as np

out = df[~np.isin(np.arange(len(df)), [i, j])]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading