0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.