DougKruger
DougKruger

Reputation: 4624

Deleting DataFrame row in Pandas where column value in list

How to remove certain rows in Pandas dataframe where column value is in list? For example:

given mylist = [fh3, fh1, fh4]

   id  loc_id
0  fh0  0859
1  fh1  5861
2  fh2  2585
3  fh3  853
4  fh4  45596
4  fh5  586

remove rows where id in mylist:

   id  loc_id
0  fh0  0859
2  fh2  2585
4  fh5  586

Upvotes: 2

Views: 212

Answers (1)

jezrael
jezrael

Reputation: 863511

Use isin with boolean indexing:

mylist = ['fh3', 'fh1', 'fh4']
print (df[~df.id.isin(mylist)])
    id  loc_id
0  fh0     859
2  fh2    2585
4  fh5     586

Another solution with drop:

mylist = ['fh3', 'fh1', 'fh4']
print (df.set_index('id').drop(mylist).reset_index())
    id  loc_id
0  fh0     859
1  fh2    2585
2  fh5     586

Upvotes: 4

Related Questions