3

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 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

Try using a list comprehension like this:

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

1 Comment

ok deleteing! good luck and thank you for contributing to the community!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.