Using Pandas GroupBy Transform Function
In this example we demonstrate how to use the groupby transform function from Pandas and add the outputs to the original dataframe.
We first create a dataframe players that contains the points and assists of 3 players over different games. We want to create two additional columns total_points and total_assists for each player that is added to the players dataframe. To do this we use groupby transform.
Groupby transform applies a function to each column in the dataframe in turn and returns a series that is the same length as the original dataframe but with values groupby whatever column(s) we pass to the groupby function.
In the below example, we show two equivalent ways to sum the points and assist columns grouped by each player using both a lambda function and a regular function. The outputs of the groupby transform function are then declared as new columns total_points and total_assists in the players dataframe. Finally we show how to groupby transform only the points column.