Pandas groupby and aggregation output should include all the original columns (including the ones not aggregated on)

前端 未结 2 1981
孤城傲影
孤城傲影 2020-12-03 11:21

I have the following data frame and want to:

  • Group records by month
  • Sum QTY_SOLDand NET_AMT of each unique
2条回答
  •  佛祖请我去吃肉
    2020-12-03 12:02

    I am thinking about this long time, thanks for your question push me to make it .By using agg and if...else

    df.groupby(['month', 'UPC_ID'],as_index=False).agg(lambda x : x.sum() if x.dtype=='int64' else x.head(1))
    Out[1221]: 
       month  UPC_ID UPC_DSC     D_DATE  QTY_SOLD  NET_AMT
    0      2     111   desc1 2017-02-26         2       10
    1      2     222   desc2 2017-02-26         3       15
    2      2     333   desc3 2017-02-26         1        4
    3      3     111   desc1 2017-03-01         5       25
    

提交回复
热议问题