Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply different aggregations to groups of pandas GroupBy

Tags:

python

pandas

I have a dataframe like

     A     B    C   D
one  2  10.0    0  11
two  5   NaN  NaN   8

and did a groupby with

df.groupby(np.array(['min', 'max', 'min', 'max']), axis=1)

Now I want to aggregate the groups with different functions. The 'min' group shall be aggregated with .sum(axis=1) while the 'max' group shall be aggregated with .sum(axis=1, skipna=False). The desired output would be

     min  max
one    2   21
two    5  NaN

Is there any built-in way to do this?

like image 719
Credics Avatar asked Dec 05 '25 18:12

Credics


1 Answers

I believe you need custom function, because it is not built-in:

def f(x):
    if x.name == 'min':
        return x.sum(axis=1)
    elif x.name == 'max':
        return x.sum(axis=1, skipna=False)

df = df.groupby(['min', 'max', 'min', 'max'], axis=1).apply(f)
print (df)
      max  min
one  21.0  2.0
two   NaN  5.0
like image 55
jezrael Avatar answered Dec 08 '25 07:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!