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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With