0

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:

python dataframe pandas drop column using int

3
  • what is irange? Commented Apr 8, 2024 at 10:15
  • a list of integers like [1, 4, 5] Commented Apr 8, 2024 at 10:16
  • @Ahmad - Sorry, dupe was changed. (need this solution) Commented Apr 8, 2024 at 10:24

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

1 Comment

Anything incorrect in my answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.