Check if pandas column contains all elements from a list

后端 未结 7 1919
忘掉有多难
忘掉有多难 2020-12-09 03:14

I have a df like this:

frame = pd.DataFrame({\'a\' : [\'a,b,c\', \'a,c,f\', \'b,d,f\',\'a,z,c\']})

And a list of items:

let         


        
7条回答
  •  囚心锁ツ
    2020-12-09 03:51

    You can use np.intersect1d:

    import pandas as pd
    import numpy as np
    
    frame = pd.DataFrame({'a' : ['a,b,c', 'a,c,f', 'b,d,f','a,z,c']})
    letters = ['a','c']
    
    mask =  frame.a.apply(lambda x: np.intersect1d(x.split(','), letters).size > 0)
    print(frame[mask])
    
        a
    0  a,b,c
    1  a,c,f
    3  a,z,c
    

提交回复
热议问题