ben121 :
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.
HS-nebula :
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')
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=360458&siteId=1