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

前端 未结 5 609
别跟我提以往
别跟我提以往 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:01

    Another generic solution is

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

    This will give you the required output.

    UPDATED (June 2020): Introduced in Pandas 0.25.0, Pandas has added new groupby behavior “named aggregation” and tuples, for naming the output columns when applying multiple aggregation functions to specific columns.

    df.groupby(
         ['col1','col2']
     ).agg(
         sum_col3 = ('col3','sum'),
         sum_col4     = ('col4','sum'),
     ).reset_index()
    

    Refer to Link for detailed description.

提交回复
热议问题