Reputation: 2870
I'd like to use groupby on pandas dataframe, but I want to get the mean of some columns and the sum for others. Let's say we have the following dataframe:
ID A B C
1 1 1 0
1 2 3 1
1 3 6 1
4 3 2 1
4 4 1 0
6 5 1 0
6 6 6 1
6 7 2 0
I would like to groupby ID and get the mean of column "A" and the sum of the other columns(in fact I have more than 40 columns).
I'd like the result to look like this:
ID A B C
1 2 10 2
4 3.5 3 1
6 6 9 1
Thanks in advance.
Upvotes: 3
Views: 1018
Reputation: 210972
you can do it this way:
Data:
In [127]: df = pd.DataFrame(np.random.randint(0,10, (7,6)), columns=list('ABCDEF'))
...: df['ID'] = np.random.choice([1,2], len(df))
...:
In [128]: df
Out[128]:
A B C D E F ID
0 7 7 2 2 3 0 1
1 8 4 1 3 6 8 1
2 4 7 7 2 8 4 2
3 5 9 3 6 6 1 1
4 4 6 1 7 4 6 2
5 4 5 3 8 7 6 2
6 8 4 1 8 1 0 1
Solution:
In [129]: fnc = {c:'sum' for c in df.columns.drop(['ID','A'])}
...: fnc['A'] = 'mean'
...:
In [130]: fnc
Out[130]: {'A': 'mean', 'B': 'sum', 'C': 'sum', 'D': 'sum', 'E': 'sum', 'F': 'sum'}
In [131]: df.groupby('ID').agg(fnc).reindex_axis(df.columns.drop('ID'), 1)
Out[131]:
A B C D E F
ID
1 7 24 7 19 16 9
2 4 18 11 17 19 16
Upvotes: 6