Search code examples
pythonsumpandas-groupbyaggregate

groupby agg (return the same value for selected columns while others sum)


I have Panda's groupby function, and I would like the Name and Phone columns to just copy the values, while for the Income it would sum. But this lambda function doesn't work for me

df.groupby('ID').agg({'Name' : lambda x: x,
                 'Income' : 'sum',
                 'Phone' : lambda x: x})

Solution

  • Try something like:

    df.groupby('ID').agg({'Name' : 'first',
                     'Income' : 'sum',
                     'Phone' : 'first'})