Search code examples
pythonstringpandasseries

'and' operator in string.contains


I have a pandas series in which I am applying string search this way

df['column_name'].str.contains('test1')

This gives me true/false list depending on string 'test1' is contained in column 'column_name' or not.

However I am not able to test two strings where I need to check if both strings are there or not. Something like

  df['column_name'].str.contains('test1' and 'test2')

This does not seem to work. Any suggestions would be great.


Solution

  • No you have to create 2 conditions and use & and wrap parentheses around the conditions due to operator precedence:

    (df['column_name'].str.contains('test1')) & (df['column_name'].str.contains('test2))
    

    If you wanted to test for either word then the following would work:

    df['column_name'].str.contains('test1|test2')