python lamba - if statement with conditions in multiple columns

Viewed 191

I have a dataframe:

df = pd.DataFrame({'col1': [1,2,3,4,5], 'col2':[1,2,3,4,5], 'col3':['a','b','c','d','e']})

I want to create a new column that says 'yes' if col1 and col2 are equal to 1 else it would say no.

I have tried using a lambda function but no success:

df['win'] = df[['col1', 'col2']].apply(lambda x: 'Yes' if (x['col1'] == 1) & (x['col2'] == 1) else 'No')

Is there a better way of doing this? or an improvement on what I have done so it works.

3 Answers

You can check if the two columns are equal to 1, and perform a row-wise and then perform a mapping to Yes and No:

df['win'] = df[['col1', 'col2']].eq(1).all(axis=1).replace({True: 'Yes', False: 'No'})

This will, for large dataframes, be faster, since it the operations are done in "bulk".

Yes, you can use np.where.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1': [1,2,3,4,5], 'col2':[1,2,3,4,5], 'col3':['a','b','c','d','e']})

condition = ((df['col1'] == 1) & (df['col2'] == 1))
# Return 'Yes' if the condition is True, and 'No' if False
df['win'] = np.where(condition, 'Yes', 'No')

It's better if you create a function for that, than apply lambda on axis 1:

def yes_no(x):
 if (x['col1'] == 1) & (x['col2'] == 1):
   return 'Yes'
 else:
   return 'No'

Then apply lambda on axis = 1:

df['win'] = df.apply(lambda x: yes_no(x), axis = 1)
Related