Borut Flis
Borut Flis

Reputation: 16375

How can you call different aggregate operations on pandas groubpy object

df.groupby("home_team_name")["home_team_goal_count","away_team_goal_count"].sum()

I want to group examples in my data-frame based on the variable home_team_name I would like to perform different operations on different attributes. I want sum one of them and mean for one of them and the last occurence for another.

As of now I only know how to perform the same operation on all of them like in my code example.

Upvotes: 0

Views: 23

Answers (1)

YOLO
YOLO

Reputation: 21719

You can do:

import numpy as np
df.groupby("home_team_name").agg({'home_team_goal_count': sum,
                                  'away_team_goal_count': np.mean})

Refer to more examples in documentation

To get the last value, you could do:

df.groupby("home_team_name").agg({'home_team_goal_count': 'last',
                                      'away_team_goal_count': 'last'})

Upvotes: 1

Related Questions