在多列中包含条件的python lamba-if语句
我有一个数据帧:在多列中包含条件的python lamba-if语句,python,pandas,Python,Pandas,我有一个数据帧: df = pd.DataFrame({'col1': [1,2,3,4,5], 'col2':[1,2,3,4,5], 'col3':['a','b','c','d','e']}) 我想创建一个新列,如果col1和col2等于1,它会说“是”,否则它会说“否” 我尝试过使用lambda函数,但没有成功: df['win'] = df[['col1', 'col2']].apply(lambda x: 'Yes' if (x['col1'] == 1) & (x['co
df = pd.DataFrame({'col1': [1,2,3,4,5], 'col2':[1,2,3,4,5], 'col3':['a','b','c','d','e']})
我想创建一个新列,如果col1和col2等于1,它会说“是”,否则它会说“否”
我尝试过使用lambda函数,但没有成功:
df['win'] = df[['col1', 'col2']].apply(lambda x: 'Yes' if (x['col1'] == 1) & (x['col2'] == 1) else 'No')
有更好的方法吗?或者对我所做的工作进行改进,使其有效 您可以检查这两列是否等于
1
,然后按行执行,然后执行到Yes
和No
的映射:
df['win'] = df[['col1', 'col2']].eq(1).all(axis=1).replace({True: 'Yes', False: 'No'})
对于大型数据帧,这将更快,因为操作是“批量”完成的。如果为此创建函数,比在轴1上应用lambda更好:
def yes_no(x):
if (x['col1'] == 1) & (x['col2'] == 1):
return 'Yes'
else:
return 'No'
然后在轴=1上应用lambda:
df['win'] = df.apply(lambda x: yes_no(x), axis = 1)
是的,您可以使用
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')
虽然您不应该对此操作使用apply,但逻辑上您的apply是正确的。但是,您需要添加
axis=1
作为参数,以便它知道如何按行缓慢地进行计算:(