How to delete line from a dataframe based on a python list?

Asked

Viewed 531 times

1

I would like to know how to delete lines from a dataframe based on the accuracy of the values of a column and a list. For example:

df: 
cod letra
101  a
202  b
303  c
404  d
505  e

lista = list([202,505])

The result I expect is:

df_saida:
cod letra
101  a
303  c
404  d

1 answer

0

Can do using .isin(), in this way:

df_saida = df.loc[~df['cod'].isin(lista)]
#output:
    cod letra
0   101 a
2   303 c
3   404 d

The .isin() here returns a Boolean list showing which values are found in the column Cod

df['cod'].isin(lista)
#output:
0    False
1     True
2    False
3    False
4     True

with the ~ we invert this selection, to pick the ones that are not in the list

~df['cod'].isin(lista)
#output:
0     True
1    False
2     True
3     True
4    False

Browser other questions tagged

You are not signed in. Login or sign up in order to post.