Saeed
Saeed

Reputation: 75

Aggregation on multiple columns in a pandas dataframe

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

Upvotes: 2

Views: 2784

Answers (2)

cs95
cs95

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

akuiper
akuiper

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

Related Questions