Pandas - dataframe groupby - how to get sum of multiple columns

前端 未结 5 621
别跟我提以往
别跟我提以往 2020-12-05 02:34

This should be an easy one, but somehow I couldn\'t find a solution that works.

I have a pandas dataframe which looks like this:

index col1   col2            


        
5条回答
  •  广开言路
    2020-12-05 03:06

    By using apply

    df.groupby(['col1', 'col2'])["col3", "col4"].apply(lambda x : x.astype(int).sum())
    Out[1257]: 
               col3  col4
    col1 col2            
    a    c        2     4
         d        1     2
    b    d        1     2
         e        2     4
    

    If you want to agg

    df.groupby(['col1', 'col2']).agg({'col3':'sum','col4':'sum'})
    

提交回复
热议问题