How do I delete a row of indexes with the starting and ending index in a dataframe(python)?

Viewed 748

For example:

INDEX FRUIT

0: "banana"

1: "apple"

2: "donut"

3: "pizza"

4: "noodles"

5: "ice-cream"

6: "grapefruit"

Usually, in order to drop rows 2-5 inclusive, I use drop.(df.index[[2,3,4,5]]) However, for the project I'm doing, the dataframe is much larger and I would have to list out all the indexes to drop a lot of rows, which is really inefficient and time-consuming. Is there a quicker and shorter way to just drop the rows using only the start and end index (in this case 2 and 5). Btw, my indexes are the default one, starting from 0, 1, 2 …

Is there a line of code or way to do that? Thanks!

2 Answers

Can also;

df.drop(df.loc[2:5].index, inplace=True)

or

df.drop(df.iloc[2:6].index, inplace=True)

df.iloc[range].index and df.loc[range] selects the index needed. Please remember .iloc operates like python range(start, range), it excluded the last index. If using it you have to go range(start, range+1)

  • you can use df.drop(df.index[x:y]) here x is inclusive and y is exclusive, so it will delete the rows which start index from x and end index y-1
start = 2
end = 5
df.drop(df.index[start:end+1])`
  • The above code will drop rows 2-5 inclusive.

I hope it helps!

Related