Python 3.x 根据A列和A列中的值填写C列;B使用数据帧
我试图在pandas数据框架中创建一个新列,其值基于其他两列的值 我尝试使用嵌套的if语句来检查每列中的值,但结果只检查第一行,并根据第一个条目填充其余行Python 3.x 根据A列和A列中的值填写C列;B使用数据帧,python-3.x,pandas,Python 3.x,Pandas,我试图在pandas数据框架中创建一个新列,其值基于其他两列的值 我尝试使用嵌套的if语句来检查每列中的值,但结果只检查第一行,并根据第一个条目填充其余行 if np.where(df['Person A']=='Yes'): if np.where(df['Person B']=='Yes'): df['Consensus'] = 'Person A said yes, then Person B said yes' elif np.where(df['Pers
if np.where(df['Person A']=='Yes'):
if np.where(df['Person B']=='Yes'):
df['Consensus'] = 'Person A said yes, then Person B said yes'
elif np.where(df['Person B']=='No'):
df['Consensus'] = 'Person B said yes, then person B said no'
让我知道如果我能澄清任何事情-我是第一次 这里有一个建议的解决方案:为您的逻辑创建一个函数,并将其应用于数据帧 执行:
df = pd.DataFrame({"Person A":["Yes","Yes","Yes","Yes","No","No"],
"Person B":["Yes","Yes","No","No","No","No"]})
yes = 'Person A said yes, then Person B said yes'
no = 'Person A said yes, then person B said no'
Person A Person B
0 Yes Yes
1 Yes Yes
2 Yes No
3 Yes No
4 No No
5 No No
def yourfunc(row):
if row['Person A']=="Yes" and row['Person B']=="Yes":
return yes
if row['Person A']=="No" and row['Person B']=="No":
return no
return "TBA"
df['Consensus'] = df.apply(yourfunc, axis=1)
Person A Person B Consensus
0 Yes Yes Person A said yes, then Person B said yes
1 Yes Yes Person A said yes, then Person B said yes
2 Yes No TBA
3 Yes No TBA
4 No No Person A said yes, then person B said no
5 No No Person A said yes, then person B said no
同路人
def f(x,y):
if x =='Yes':
if y =='Yes':
return 'Person A said yes, then Person B said yes'
elif y =='No':
return = 'Person B said yes, then person B said no'
df['Consensus'] = df.apply(lambda row: f(row['Person A'], row['Person B']), axis=1)
添加一些示例数据,以及您的预期输出