【问题标题】:Using groupby to calculate cum sum in pandas dataframe使用 groupby 计算 pandas 数据框中的 cum sum
【发布时间】: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


    【解决方案1】:

    你需要

    df_a.groupby(['Location','User']).Qty.cumsum()
    0    10
    1     8
    2     3
    3     4
    4    -1
    5     6
    Name: Qty, dtype: int64
    
    df_a['cumSum']= df_a.groupby(['Location','User']).Qty.cumsum()
    

    【讨论】:

    • 嗨,有没有一种方法可以让我在维护其他列的同时做到这一点?
    • @rain123 你可以把它分配回去,也检查更新
    • 太棒了!这正是我想要的。感谢您的帮助!
    • @rain123 Yw :-),顺便说一句,您愿意投票并接受吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2017-01-26
    • 2017-01-01
    相关资源
    最近更新 更多