【问题标题】:Pandas dataframe row operation with a condition带有条件的 Pandas 数据框行操作
【发布时间】:2022-10-21 21:17:39
【问题描述】:

我有一个数据框,其中包含有关股票的信息,如下所示:

Product ID Initial stock Initial unit cost Reference Quantity Unit cost Current stock
a 5 22 Purch. 4 24 9
a 5 22 Purch. 8 21 17
a 5 22 Sale -4 25 13
a 5 22 Purch. 10 20 23
a 5 22 Sale -15 22 8
b 14 3.5 Sale 10 4 4
b 14 3.5 Purch. 20 3 24
b 14 3.5 Sale 5 4 19
b 14 3.5 Purch. 2 3.5 21
c 27 1 Purch. 100 0.95 127
c 27 1 Purch. 3 1.1 130

每行代表特定产品的购买/销售。 Quantity 表示在给定的Unit cost 购买/出售的单位数量。 Current stock 是购买/出售后的剩余库存。对于每种产品,我想在每次销售/购买后计算加权平均成本 (WAC)。程序如下:

  • 对于每个产品的第一行,WAC = (Initial stock * Initial unit cost + Quantity * Unit cost) / Current stock 就像Reference == 'Purch.' 一样。如果没有,WAC = Initial unit cost

  • 对于下一行,WAC[i] = (Current stock[i-1] * WAC[i-1] + Quantity[i] * Unit cost[i]) / Current stock[i]Reference[i] == 'Purch.' 相同。如果没有,WAC[i] = WAC[i-1]

下表显示了我正在寻找的内容(WAC 列以及如何计算它):

Product ID Initial stock Initial unit cost Reference Quantity Unit cost Current stock (how to) WAC WAC
a 5 22 Purch. 4 24 9 (5*22 + 4*24)/9 22.89
a 5 22 Purch. 8 21 17 (9*22.89 + 8*21)/17 22
a 5 22 Sale -4 25 13 - 22
a 5 22 Purch. 10 20 23 (13*22 + 10*20)/23 21.13
a 5 22 Sale -15 22 8 - 21.13
b 14 3.5 Sale 10 4 4 - 3.5
b 14 3.5 Purch. 20 3 24 (4*3.5 + 20*3)/24 3.08
b 14 3.5 Sale 5 4 19 - 3.08
b 14 3.5 Purch. 2 3.5 21 (19*3.08 + 2*3.5)/21 3.12
c 27 1 Purch. 100 0.95 127 (27*1 + 100*0.95)/127 0.96
c 27 1 Purch. 3 1.1 130 (127*0.96 + 3*1.1)/130 0.96

你会如何使用 Pandas 来实现它?我尝试使用 groupby 和 cumsum,但我不知道如何引入“if”语句。在那之后,我想总结一下信息,只得到Product ID以及最后的StockWAC,就像这样:

Product ID Current stock WAC
a 8 21.13
b 21 3.12
c 130 0.96

先感谢您!

【问题讨论】:

    标签: python pandas if-statement group-by


    【解决方案1】:

    希望我理解你的问题是正确的。

    代码:

    #Create new columns using lambda function
    
    df['(how to)WAC']= df.apply(lambda row: (row['Intial stock']*row['Intial unit cost']+row['Quantity']*row['Unit cost'])/row['Current stock'] if row['Reference']=='Purch' else 0, axis=1)
    df['WAC']        = df.apply(lambda row: row['(how to)WAC'] if row['(how to)WAC']!=0 else row['Initial unit cost'],axis=1)
    
    
    
    #Group by the ID and display the last rows of each
    df.groupby('id').tail(1)[['Product ID','Current stock', 'WAC']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 2019-02-27
      • 2018-05-04
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      相关资源
      最近更新 更多