虽然我希望以理想的方式用熊猫来实现,但这更多是算法问题,我想知道你们中的一些人是否有建议。问题如下:
一个表按日期,项目,数量(购买时为+,销售时为-)和价格包含产品的购买和销售。
条件:
具有单个产品的示例:
date product quantity price
1 X +2 1
1 X -1 2
1 X -1 4
2 X +1 1
2 X +1 2
3 X -1 4
答案:结果将是仅在第1天匹配3笔交易,获利为-2 + 2 + 4 = 4
product Profit
X +4
尝试一下:
# Just creating the data
df = pd.DataFrame({'date': [1,1,1,2,2,3],
'product': 'X',
'quantity': [2,-1,-1, 1, 1,-1],
'price': [1,2,4,1,2,4]})
df['total'] = -df.quantity * df.price
profit = df.groupby(['product', 'date']).agg(total=('total', 'sum'))
print(profit)
total
product date
X 1 4
2 -3
3 4
这将返回一个新的数据框,其中日期和产品作为索引,相应的利润显示在一栏中。