对另一列使用if语句在dataframe中创建新列

2024-05-03 06:03:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在计算中使用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

这就是我需要的

列=价格

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

我如何做到这一点


Tags: 数据dfif价格discountiifordernumunitprice
2条回答

您也可以使用这两条语句

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

但如果折扣等于零,则-(折扣/订单数量)将为零,是否需要?所以我想这也可以:

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

尝试:

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

相关问题 更多 >