Pandas aggregate with function with multiple parameters

Viewed 11
df = pd.DataFrame({'a': list('aabb'), 'b': [1, 2, 3, 4], 'c': [4, 2, 1, 3]})

def agg_func(x, y):
    return sum(x) > sum(y)

I need smth like that

df.groupby('a').agg({('b', 'c'): agg_func})

And expect

enter image description here

1 Answers

Here I would simple aggregate the columns, and then perform the comparison:

g = df.groupby('a').sum()
out = g['b']>g['c']

With your function (probably less efficient):

out = df.groupby('a').apply(lambda g: agg_func(g['b'], g['c']))

output:

a    False
b     True
dtype: bool
Related