【发布时间】:2020-07-12 16:32:01
【问题描述】:
我有下面的数据框,我打算计算累积总和:
df_a = pd.DataFrame({'Location': ['SR01','SR01','SR02','SR01','SR01','SR02'],
'User':['101','101','101','102','102','102'],
'Year':['2018','2019','2019','2018','2019','2019'],
'Month':[12, 1, 2, 12, 1, 2],
'Qty':[10, -2, 3, 4, -5, 6]})
我的预期输出如下:
df_a = pd.DataFrame({'Location': ['SR01','SR01','SR02','SR01','SR01','SR02'],
'User':['101','101','101','102','102','102'],
'Year':['2018','2019','2019','2018','2019','2019'],
'Month':[12, 1, 2, 12, 1, 2],
'Qty':[10, -2, 3, 4, -5, 6],
'CumSum': [10, 8, 3, 4, -1, 6]})
但是,当我使用 df_a.groupby(['Location','User','Year','Month']).sum().groupby(level=1).cumsum() 时,我得到了这个:
df_a = pd.DataFrame({'Location': ['SR01','SR01','SR02','SR01','SR01','SR02'],
'User':['101','101','101','102','102','102'],
'Year':['2018','2019','2019','2018','2019','2019'],
'Month':[12, 1, 2, 12, 1, 2],
'Qty':[10, 8, 4, -1, 11, 5]})
有人可以解释为什么我的代码不起作用并解决这个问题吗?
【问题讨论】:
标签: python pandas cumulative-sum