假设我有下表:
multiply total tax
Y 500 .1
Y 250 .5
N 300 .5
仅当乘法值为Y时,我才希望将总计设置为总计*税额
最终输出:
multiply total tax
Y 50 .1
Y 125 .5
N 300 .5
答案 0 :(得分:4)
使用np.where
df['total'] = np.where(df['multiply'] == 'Y', df['total'] * df['tax'], df['total'])
print(df)
multiply total tax
Y 50.0 0.1
Y 125.0 0.5
N 300.0 0.5
答案 1 :(得分:1)
可以这样做
df.loc[df['multiply'] == 'Y', 'total'] = df.loc[df['multiply'] == 'Y', 'total'] * df.loc[df['multiply'] == 'Y', 'tax']
df.where(df['multiply'] == 'N', df.assign(total = df['total'] * df['tax']))
输出:
multiply total tax
0 Y 50 0.1
1 Y 125 0.5
2 N 300 0.5
答案 2 :(得分:1)
我们在这里哥们
df.loc[df.multiply == 'Y', 'total'] = df.loc[df.multiply == 'Y', 'total'] * df.loc[df.multiply == 'Y', 'tax']
答案 3 :(得分:1)
df=pd.DataFrame({'multiply':['Y','Y','N'],'total':[500,250,300],'tax':[.1,.5,.5]})
def myfunc(row):
if(row[0]=='Y'):
return float(row[1])*float(row[2])
return row[2]
df['total']=df.apply(lambda x: myfunc(x),axis=1)
df
输出
multiply tax total
0 Y 0.1 50.0
1 Y 0.5 125.0
2 N 0.5 300.0