首页 > 解决方案 > Pandas 条件计算 | 交易单的剩余供应

问题描述

我有一个列出产品交易的数据框。它显示了每种产品的价值以及交易中包含的数量。

# Input: Transaction Sheet

      Products     Single Value      Amount      Type         
0     Prod1          -112,20          15,00      Buy   
1     Prod1         -221,84           12,00      Sell  
2     Prod1          339,93           48,00      Buy
3     Prod1         -855,50           13,00      Buy
4     Prod1           68,40           90,00      Buy
5     Prod1           45,1            10,00      Sell
..    ....           .......       ........      ....
8     Prod1         1.179,10          12,00      Sell
9     Prod1         -355,52           15,00      Buy
10    Prod1          -23,23           18,00      Sell
11    Prod1         -3235,33         300,00      Sell

我想在最后得到一行来表示产品的当前库存。如果库存中没有更多产品,则不应创建数据框。但如果有库存,则应在此处表示产品的剩余价值和数量。

# Output: Remaining inventory and average purchase price


      Products     Average Value      Amount         
0     Prod1          -112,20          15,00 

如果我不使用 pandas,我将简单地遍历行并添加/减去现有集。如果最后还有存货,我会计算最后一次总销售前所有交易的平均值。

我还没有找到用 pandas 解决这个问题的可行方法——这对我来说很新鲜。谁能帮我实现这样的计算?

标签: pythonpandas

解决方案


这是一个尝试使用 cumsum() 函数来获取您手头的库存。我还没有对产品进行分组,所以这实际上可能是朝着错误方向迈出的一步。尽管如此,这里还是要讨论的:

import pandas as pd


def get_change(amount, type): 
  if type  == 'Buy':  
    return amount
  else:  
    return -amount



df = pd.DataFrame( {
  'Products': ['Prod1'] * 10 , 
  'Single Value': ['-112.2',  '-221.84',  '339.93',  '-855.5',  '68.4',  '45.1',  '1.179.10',  '-355.52',  '-23.23',  '-3235.33'], 
  'Amount': [ 15,  12,  48,  13,  90,  10,  12,  15,  18,  300], 
  'Type': [ 'Buy',  'Sell',  'Buy',  'Buy',  'Buy',  'Sell',  'Sell',  'Buy',  'Sell',  'Sell']
} )

df['change'] = df.apply( lambda row : get_change( row['Amount'], row['Type'] ), axis = 1 )
df['onhand'] = df['change'].cumsum() 
print(df)

产量:

  Products Single Value  Amount  Type  change  onhand
0    Prod1       -112.2      15   Buy      15      15
1    Prod1      -221.84      12  Sell     -12       3
2    Prod1       339.93      48   Buy      48      51
3    Prod1       -855.5      13   Buy      13      64
4    Prod1         68.4      90   Buy      90     154
5    Prod1         45.1      10  Sell     -10     144
6    Prod1     1.179.10      12  Sell     -12     132
7    Prod1      -355.52      15   Buy      15     147
8    Prod1       -23.23      18  Sell     -18     129
9    Prod1     -3235.33     300  Sell    -300    -171

也就是说,这仅在产品相同时才对我有用(就像在您的数据示例中一样)。实验groupby('Products')并没有产生我在手头专栏中寻找的结果。由于进展有限,我将把它作为一种方法提交——也许不是一种可行的方法。


推荐阅读