Pandas Group By and Sum Every N rows

后端 未结 1 625
北恋
北恋 2021-01-28 06:30

I have time series data and I want to group by and calculate the sum every 3 rows. Seems like a straightforward task but I\'m not able to figure it out. I would appreciate your

1条回答
  •  清酒与你
    2021-01-28 06:52

    First elevate your index to a series. Then use groupby + agg with a dictionary:

    df = df.reset_index()
    
    d = {'DATE': 'last', 'AE_NAME': 'last', 'ANSWERED_CALL': 'sum'}
    
    res = df.groupby(df.index // 3).agg(d)
    
    print(res)
    
            DATE       AE_NAME  ANSWERED_CALL
    0 2018-10-10  AlecSochacki           15.0
    1 2018-10-15  AlecSochacki           12.0
    2 2018-10-18  AlecSochacki           16.0
    3 2018-10-19  AlecSochacki            7.0
    

    You've got some unclear logic for the first row, so you may need one or two more operations.

    0 讨论(0)
提交回复
热议问题