Reputation: 1601
Let's say I have the following table:
multiply total tax
Y 500 .1
Y 250 .5
N 300 .5
I want to set the total to total * tax only if the value of multiply is Y
Final output:
multiply total tax
Y 50 .1
Y 125 .5
N 300 .5
Upvotes: 1
Views: 176
Reputation: 5437
It can be done like that
df.loc[df['multiply'] == 'Y', 'total'] = df.loc[df['multiply'] == 'Y', 'total'] * df.loc[df['multiply'] == 'Y', 'tax']
Another approach using pandas where and assign could be:
df.where(df['multiply'] == 'N', df.assign(total = df['total'] * df['tax']))
Outputs:
multiply total tax
0 Y 50 0.1
1 Y 125 0.5
2 N 300 0.5
Upvotes: 1
Reputation: 8273
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
Output
multiply tax total
0 Y 0.1 50.0
1 Y 0.5 125.0
2 N 0.5 300.0
Upvotes: 1
Reputation: 1607
use 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
Upvotes: 4
Reputation: 19375
here we go buddy
df.loc[df.multiply == 'Y', 'total'] = df.loc[df.multiply == 'Y', 'total'] * df.loc[df.multiply == 'Y', 'tax']
Upvotes: 1