Pandas Search Specific Columns for String

Viewed 144

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
2 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

Try using a list comprehension like this:

df['Result'] = ['Yes' if len(i) >= 1 else 'No' for i in df.values.tolist()]
Related