Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter data frame based on index values in a separate list?

Tags:

python

pandas

I have a list (list1) that looks like this:

  ['loc1','loc3','loc6'.....]

I also have a data frame (df1) that looks like this:

        Values    Proportion
loc1    200          10
loc2    50           20
loc3    100          30
loc4    60           45
loc5    70           12
loc6    80           11
loc7    10           10
.... 

I want to remove the rows where my index in the data frame matches values in the list. The resultant output file:

        Values    Proportion
loc2    50           20
loc4    60           45
loc5    70           12
loc7    10           10
.... 

My solution would be (but doesn't work).

reduced_file = set(df1.index) - list1
like image 583
Alex Trevylan Avatar asked Sep 16 '25 09:09

Alex Trevylan


1 Answers

Try it like this:

df.loc[~df.index.isin(list1)]
like image 166
zipa Avatar answered Sep 19 '25 03:09

zipa