Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by and aggregate on multiple columns in pandas

I have following dataframe in pandas

 ID     Balance     ATM_drawings    Value
 1      100         50              345 
 1      150         33              233
 2      100         100             333 
 2      100         100             234

I want data in that desired format

 ID     Balance_mean    Balance_sum     ATM_Drawings_mean    ATM_drawings_sum 
 1      75              250             41.5                 83 
 2      200             100             200                  100

I am using following command to do it in pandas

 df1= df[['Balance','ATM_drawings']].groupby('ID', as_index = False).agg(['mean', 'sum']).reset_index()

But, it does not give what I intended to get.

like image 645
Neil Avatar asked Aug 02 '18 12:08

Neil


1 Answers

You can use a dictionary to specify aggregation functions for each series:

d = {'Balance': ['mean', 'sum'], 'ATM_drawings': ['mean', 'sum']}
res = df.groupby('ID').agg(d)

# flatten MultiIndex columns
res.columns = ['_'.join(col) for col in res.columns.values]

print(res)

    Balance_mean  Balance_sum  ATM_drawings_mean  ATM_drawings_sum
ID                                                                
1            125          250               41.5                83
2            100          200              100.0               200

Or you can define d via dict.fromkeys:

d = dict.fromkeys(('Balance', 'ATM_drawings'), ['mean', 'sum'])
like image 103
jpp Avatar answered Oct 26 '22 06:10

jpp