Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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.

like image 930
PagMax Avatar asked Feb 07 '26 16:02

PagMax


2 Answers

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')
like image 54
EdChum Avatar answered Feb 09 '26 07:02

EdChum


all( word in df['column_name'] for word in ['test1', 'test2'] )

this will test an arbitrary number or words present in a string

like image 35
user2255757 Avatar answered Feb 09 '26 07:02

user2255757