Reputation: 10697
I have this data frame:
>>> df = pd.DataFrame({'c1':['a','a','a','a','b','b','b','b'], 'c2':['x','y','x','y','x','y','x','y'], 'sum':[1,1,0,1,0,0,1,0], 'mean':[12,14,11,13,12,23,12,31]})
I'm trying to use two separate aggregate functions and I know I can do this:
>>> df.groupby(['c1','c2'])['sum','mean'].agg([np.sum,np.mean])
>>> df
sum mean
sum mean sum mean
c1 c2
a x 1 0.5 23 11.5
y 2 1.0 27 13.5
b x 1 0.5 24 12.0
y 0 0.0 54 27.0
but it creates the unnecessary "mean" column in sum
and "sum" column in mean
. Is there a way to achieve this result:
sum mean
c1 c2
a x 1 11.5
y 2 13.5
b x 1 12.0
y 0 27.0
I tried:
>>> df.groupby(['c1','c2'])['sum','mean'].agg({'sum':np.sum, 'mean':np.mean})
but it raises a KeyError
exception.
Upvotes: 0
Views: 247
Reputation: 24742
You can pass a dict to .agg
with {column_name: agg_func}
df.groupby(['c1', 'c2']).agg({'mean': np.mean, 'sum': np.sum})
sum mean
c1 c2
a x 1 11.5
y 2 13.5
b x 1 12.0
y 0 27.0
Upvotes: 1