Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Search Specific Columns for String

I am trying to search through specific columns in my DataFrame. If any of these columns contains the keyword "Matched" I would then like to write to the column "Result" with a "Yes"

Current DF

Result Google    Bing    Search
       Matched   Matched Matched

       Matched   
                         Matched

Expected Result

Result Google    Bing    Search
 Yes   Matched   Matched Matched
 No   
 Yes   Matched   
 Yes                     Matched
like image 865
Will Avatar asked Dec 01 '25 08:12

Will


1 Answers

Use numpy.where with test values by DataFrame.eq with DataFrame.any for test at least one value per row:

cols = ['Google', 'Bing', 'Search']
df['Result'] = np.where(df[cols].eq('Matched').any(axis=1), 'Yes','No')
print (df)
  Result   Google     Bing   Search
0    Yes  Matched  Matched  Matched
1     No      NaN      NaN      NaN
2    Yes  Matched      NaN      NaN
3    Yes      NaN  Matched      NaN
like image 101
jezrael Avatar answered Dec 07 '25 10:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!