Reputation: 75
z = pd.DataFrame({'a':[1,1,1,2,2,3,3],'b':[3,4,5,6,7,8,9], 'c':[10,11,12,13,14,15,16]})
gbz = z.groupby('a')
f1 = lambda x: x.loc[x['b'] > 4]['c'].mean()
f2 = lambda x: x.mean()
f3 = {'I don't know what should I write here':{'name1':f1}, 'b':{'name2': f2}}
list1 = gbz.agg(f3)
How can I put more than one column to use in function "f1" ? (This function needs two columns of the groupby object)
name1 name2
1 12.0 4
2 13.5 6.5
3 15.5 8.5
Upvotes: 2
Views: 2784
Reputation: 403218
You can use agg
with a lambda
like this:
g = z.groupby('a').agg(lambda x: [x[(x.b > 4)].c.mean(), x.b.mean()])
You'll have to rename your columns manually:
g.columns = ['name1', 'name2']
print(g)
name1 name2
a
1 12.0 4.0
2 13.5 6.5
3 15.5 8.5
Upvotes: 2
Reputation: 215127
Nested dictionary in agg
function is deprecated. What you might do is use groupby.apply
and return a properly indexed series for each group for renaming purpose:
(z.groupby('a')
.apply(lambda g: pd.Series({
'name1': g.c[g.b > 4].mean(),
'name2': g.b.mean()
})))
# name1 name2
#a
#1 12.0 4.0
#2 13.5 6.5
#3 15.5 8.5
Upvotes: 5