ybin
ybin

Reputation: 575

How to match list in multiple columns

example my dataframe,

   0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21 ...
0  A  B  C  D  E  F  G  H  I  J  K   L   M   N   O   P   Q   R   S   T   U   V
1  B  C  D  E  F  G  H  I  J  K  L   M   N   O   P   Q   R   S   T   U   V   A  
2  V  A  B  C  D  E  F  G  H  I  J   K   L   M   N   O   P   Q   R   S   T   U          

and my list

mylist = ['A', 'B' 'C']

I want to match the columns and the list so that only the characters in the list exist in the column.

output what I want

   0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21 ...
0  A  B  C  
1  B  C                                                                      A  
2     A  B  C  

I'm not sure what to do, so I ask a question. Thank you for reading.

Upvotes: 2

Views: 92

Answers (2)

jezrael
jezrael

Reputation: 862511

Use DataFrame.isin with DataFrame.where:

mylist = ['A', 'B', 'C']
df = df.where(df.isin(mylist), '')
print (df)
   0  1  2  3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
0  A  B  C                                                   
1  B  C                                                     A
2     A  B  C   

Or if invert mask is possible use:

df[~df.isin(mylist)] = ''                                             

Upvotes: 4

Sajan
Sajan

Reputation: 1267

This might also work -

df = df[df.isin(mylist)].fillna('')

Upvotes: 2

Related Questions