python - 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 解决这个问题的可行方法——这对我来说很新鲜。谁能帮我实现这样的计算?
解决方案
这是一个尝试使用 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')
并没有产生我在手头专栏中寻找的结果。由于进展有限,我将把它作为一种方法提交——也许不是一种可行的方法。
推荐阅读
- sql-server - 将数据从 Access 导出到现有的 SQL Server 数据库表?
- groovy - 在groovy中使用附加节点操作列表
- android - 本机脚本。AAPT:错误:未找到样式属性“android:attr/forceDarkAllowed”
- android - NoSuchMethodError:类“_Type”没有实例获取器“imgPath”
- python - 给定一个向量或列表,如何制作一个从一个开始的数字填充的对称矩阵?
- git - bitbucket.org:权限被拒绝(公钥)
- python-3.x - 将大量数据(字典)转换为表格
- javascript - 当我使用@react-google-maps/api 时,为什么 react-select 会中断?
- python - 我的 SPSA(同时扰动随机近似优化器)的实现有什么问题?
- r - 从 markdown 到 Word 的表格看起来没有格式化