0

I know how to delete rows and columns from a dataframe using .drop() method, by passing axis and labels.

Here's the Dataframe:

enter image description here

Now, if i want to remove all rows whose STNAME is equal to from (Arizona all the way to Colorado), how should i do it ?

I know i could just do it by passing row labels 2 to 7 to .drop() method but if i have a lot of data and i don't know the starting and ending indexes, it won't be possible.

Kakarot_7
  • 302
  • 1
  • 5
  • 14
  • 1
    https://stackoverflow.com/questions/52456874/drop-rows-on-multiple-conditions-in-pandas-dataframe – Edeki Okoh May 06 '20 at 19:38
  • You mean that in this case, all rows where STNAME = Arizona, California and Colorado should be deleted? And if you'd give it Arizona and Georgia, every row with STNAME between Arizona and Georgia should be deleted? – sander May 06 '20 at 19:42
  • Does this answer your question? [Drop rows on multiple conditions in pandas dataframe](https://stackoverflow.com/questions/52456874/drop-rows-on-multiple-conditions-in-pandas-dataframe) – Vaccano May 06 '20 at 22:54

1 Answers1

0

Might be kinda hacky, but here is an option:

index1 = df.index[df['STNAME'] == 'Arizona'].tolist()[0]
index2 = df.index[df['STNAME'] == 'Colorado'].tolist()[-1:][0]

df = df.drop(np.arange(index1, index2+1))

This basically takes the first index number of Arizona and the last index number of Colorado, and deletes every row from the data frame between these indexes.

sander
  • 1,340
  • 1
  • 10
  • 20