簡體   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