2

I am trying to calculate additional metrics from existing pandas dataframe by using an if/else condition on existing column values.

if(df['Sell_Ind']=='N').any():
    df['MarketValue'] = df.apply(lambda row: row.SharesUnits * row.CurrentPrice, axis=1).astype(float).round(2)
elif(df['Sell_Ind']=='Y').any():
    df['MarketValue'] = df.apply(lambda row: row.SharesUnits * row.Sold_price, axis=1).astype(float).round(2)
else:
    df['MarketValue'] = df.apply(lambda row: 0)

For the if condition the MarketValue is calculated correctly but for the elif condition, its not giving the correct value. Can anyone point me as what wrong I am doing in this code.

1 Answer 1

1

I think you need numpy.select, apply can be removed and multiple columns by mul:

m1 = df['Sell_Ind']=='N'
m2 = df['Sell_Ind']=='Y'
a = df.SharesUnits.mul(df.CurrentPrice).astype(float).round(2)
b = df.SharesUnits.mul(df.Sold_price).astype(float).round(2)
df['MarketValue'] =  np.select([m1, m2], [a,b], default=0)

Sample:

df = pd.DataFrame({'Sold_price':[7,8,9,4,2,3],
                   'SharesUnits':[1,3,5,7,1,0],
                   'CurrentPrice':[5,3,6,9,2,4],
                   'Sell_Ind':list('NNYYTT')})

#print (df)

m1 = df['Sell_Ind']=='N'
m2 = df['Sell_Ind']=='Y'
a = df.SharesUnits.mul(df.CurrentPrice).astype(float).round(2)
b = df.SharesUnits.mul(df.Sold_price).astype(float).round(2)
df['MarketValue'] =  np.select([m1, m2], [a,b], default=0)
print (df)
   CurrentPrice Sell_Ind  SharesUnits  Sold_price  MarketValue
0             5        N            1           7          5.0
1             3        N            3           8          9.0
2             6        Y            5           9         45.0
3             9        Y            7           4         28.0
4             2        T            1           2          0.0
5             4        T            0           3          0.0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.