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 a range of rows from dataframe?

I use the following code to drop some rows based on their position in df:

for i in irange:
    df.drop(df.iloc[i].name, inplace=True)

However, it seems I can’t do it in a loop and I get:

raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds

This other question is about columns, while mine is about rows:

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

python dataframe pandas drop column using int

>Solution :

If you want to drop indices from a list of positions, you should use:

df = pd.DataFrame({'col': 1}, index=list('abcdef'))
irange = [1, 4, 5]
df.drop(df.index[irange], inplace=True)

Note however that this requires unique indices, if not:

df = pd.DataFrame({'col': 1}, index=list('abcdef'))
irange = [1, 4, 5]
out = df.loc[np.isin(np.arange(len(df)), irange)]

Output:

   col
b    1
e    1
f    1
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