2

Data:

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]})

My code:

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)

Question:

How can I put more than one column to use in function "f1" ? (This function needs two columns of the groupby object)

Expected result:

     name1  name2
1    12.0   4
2    13.5   6.5
3    15.5   8.5

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.