【发布时间】:2019-09-27 06:13:23
【问题描述】:
我有一个这样的 Pandas 数据框:
df = pd.DataFrame({
'Date': ['2018-04-01', '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01'],
'Product': ['a', 'a', 'a', 'b', 'b'],
'Volumes': [10,30,40,50,60]})
Date Product Volumes
2018-04-01 a 10
2018-05-01 a 30
2018-06-01 a 40
2018-07-01 b 50
2018-08-01 b 60
我想创建一个列,该列仅对同一产品的所有前几个月的所有交易量求和。
期望的输出是:
df = pd.DataFrame({
'Date': ['2018-04-01', '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01'],
'Product': ['a', 'a', 'a', 'b', 'b'],
'Volumes': [10,30,40,50,60],
'Result': [10,40,80,50,110] })
Date Product Volumes Result
2018-04-01 a 10 10
2018-05-01 a 30 40
2018-06-01 a 40 80
2018-07-01 b 50 50
2018-08-01 b 60 110
有人对如何做到这一点有任何建议吗?
谢谢!
【问题讨论】:
-
使用
df['Result'] = df.groupby('Product')['Volumes'].cumsum() -
检查this