[英]Create new column in pandas dataframe using if statement against another column
I need to calculate a new column in my dataframe using a if in the calculation but have no luck with anything I have tried. 我需要在计算中使用if来计算数据框中的新列,但是我尝试过的任何方法都没有运气。 This is what I have 这就是我所拥有的
OrderNum Discount OrderQty UnitPrice REMAININGQTY
0 115702 0.0 25.0 145.00 25.0
1 115793 0.0 20.0 823.00 20.0
2 115793 0.0 20.0 823.00 20.0
3 116282 0.0 1.0 699.95 1.0
4 116765 0.0 36.0 295.00 6.0
This is what I need. 这就是我所需要的。
column = PricePer 列= PricePer
the calculation = IIf(df.discount<>0,df.unitprice-(df.discount/df.orderqty),df.unitprice)
计算= IIf(df.discount<>0,df.unitprice-(df.discount/df.orderqty),df.unitprice)
How do I accomplish this? 我该如何完成?
Try: 尝试:
df['Price Per'] = pd.np.where(df.Discount != 0, df.UnitPrice - (df.Discount / df.OrderQty), df.UnitPrice)
Output: 输出:
OrderNum Discount OrderQty UnitPrice REMAININGQTY Price Per
0 115702 0.0 25.0 145.00 25.0 145.00
1 115793 0.0 20.0 823.00 20.0 823.00
2 115793 0.0 20.0 823.00 20.0 823.00
3 116282 0.0 1.0 699.95 1.0 699.95
4 116765 0.0 36.0 295.00 6.0 295.00
You might also use these 2 statements 您可能还会使用这2条语句
df.loc[df['Discount'] == 0, 'PricePer'] = df['UnitPrice']
df.loc[df['Discount'] != 0, 'PricePer'] = df['UnitPrice']-df['Discount']/df['OrderQty']
But if discount equals zero, the -(discount / orderqty) would be zero, no if is needed ? 但是,如果折扣等于零,则-(discount / orderqty)将为零,是否不需要? So I would think this might also do: 所以我认为这可能也可以:
df['PricePer'] = df['UnitPrice']-df['Discount']/df['OrderQty']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.