简体   繁体   中英

how to use different aggregate functions for separate columns in pandas? - python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM