pandas : return YES if any of the cell in multiple columns contains a string

Viewed 20

I have a data-frame:

df = pd.DataFrame({'A': ['Target acc', 'Target acc', 'N'],
                'B': ['Target acc', 'Target acc', 'N'],
                'C': ['Target acc', 'N', 'N']})

I would like to return 'Yes' if the string 'Target acc' is present at least in of the columns (A,B,C), if no column contains the string I would like to return 'N'; The result would be:

enter image description here

How do I do it?

1 Answers

You can use:

df['D'] = np.where(df.eq('Target acc').any(axis=1), 'Yes', 'No')

If you have more columns and want to limit to A/B/C:

df['D'] = np.where(df[['A', 'B', 'C']].eq('Target acc').any(axis=1), 'Yes', 'No')

output:

            A           B           C    D
0  Target acc  Target acc  Target acc  Yes
1  Target acc  Target acc           N  Yes
2           N           N           N   No
Related