繁体   English   中英

使用if语句针对另一列在pandas数据框中创建新列

[英]Create new column in pandas dataframe using if statement against another column

我需要在计算中使用if来计算数据框中的新列,但是我尝试过的任何方法都没有运气。 这就是我所拥有的

     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

这就是我所需要的。

列= PricePer

计算= IIf(df.discount<>0,df.unitprice-(df.discount/df.orderqty),df.unitprice)

我该如何完成?

尝试:

df['Price Per'] = pd.np.where(df.Discount != 0, df.UnitPrice - (df.Discount / df.OrderQty), df.UnitPrice)

输出:

  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

您可能还会使用这2条语句

df.loc[df['Discount'] == 0, 'PricePer'] = df['UnitPrice']
df.loc[df['Discount'] != 0, 'PricePer'] = df['UnitPrice']-df['Discount']/df['OrderQty']

但是,如果折扣等于零,则-(discount / orderqty)将为零,是否不需要? 所以我认为这可能也可以:

df['PricePer'] = df['UnitPrice']-df['Discount']/df['OrderQty']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM