Check if a string in a Pandas DataFrame column is in a list of strings

后端 未结 4 1692
夕颜
夕颜 2020-11-27 14:59

If I have a frame like this

frame = pd.DataFrame({\'a\' : [\'the cat is blue\', \'the sky is green\', \'the dog is black\']})

and I want to

4条回答
  •  死守一世寂寞
    2020-11-27 15:27

    frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})
    
    frame
                      a
    0   the cat is blue
    1  the sky is green
    2  the dog is black
    

    The str.contains method accepts a regular expression pattern:

    mylist = ['dog', 'cat', 'fish']
    pattern = '|'.join(mylist)
    
    pattern
    'dog|cat|fish'
    
    frame.a.str.contains(pattern)
    0     True
    1    False
    2     True
    Name: a, dtype: bool
    

    Because regex patterns are supported, you can also embed flags:

    frame = pd.DataFrame({'a' : ['Cat Mr. Nibbles is blue', 'the sky is green', 'the dog is black']})
    
    frame
                         a
    0  Cat Mr. Nibbles is blue
    1         the sky is green
    2         the dog is black
    
    pattern = '|'.join([f'(?i){animal}' for animal in mylist])  # python 3.6+
    
    pattern
    '(?i)dog|(?i)cat|(?i)fish'
    
    frame.a.str.contains(pattern)
    0     True  # Because of the (?i) flag, 'Cat' is also matched to 'cat'
    1    False
    2     True
    

提交回复
热议问题