Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groupby in pandas with different functions for different columns

Tags:

python

pandas

Best to illustrate by example:

I would like to aggregate a DataFrame by col1 and col2, summing results on col3 and col4 and averaging results on col5

If I just wanted to sum on col3-5 I'd use df.groupby(['col1','col2']).sum()

like image 942
eran Avatar asked Dec 10 '22 20:12

eran


1 Answers

You can use the Groupby.agg() (or Groupby.aggregate()) method for this.

aggregate() function can accept a dictionary as argument, in which case it treats the keys as the column names and the value as the function to use for aggregating. As given in the documentation -

By passing a dict to aggregate you can apply a different aggregation to the columns of a DataFrame.

Example -

import numpy as np
result = df.groupby(['col1','col2']).agg({'col3':'sum','col4':'sum','col5':np.average})

Demo -

In [50]: df = pd.DataFrame([[1,2,3,4,5],[1,2,6,7,8],[2,3,4,5,6]],columns=list('ABCDE'))

In [51]: df
Out[51]:
   A  B  C  D  E
0  1  2  3  4  5
1  1  2  6  7  8
2  2  3  4  5  6

In [52]: df.groupby(['A','B']).aggregate({'C':np.sum,'D':np.sum,'E':np.average})
Out[52]:
     C    E   D
A B
1 2  9  6.5  11
2 3  4  6.0   5
like image 106
Anand S Kumar Avatar answered Dec 28 '22 23:12

Anand S Kumar