How to apply function to Python group by

How to apply function to Python group by

What is groupby in Python?

A group is an activity which includes different blend of parting an item, applying change, and joining results.

We will experience each progression however before we do that how about we load a dataset. The beneath is a depiction of all innings were two Australian batsmen scored a century.

Image for post

Suppose we want to count the total number of 4s scored by each batsman. The first step is to create a group of each player with index,

Image for post

How to unravel or view the groups created

python-group-by

for each key, here ‘Player’ it splits the dataframe and collects the index of all rows in each group to one.

Let’s print out the first element of each group.

python-group-by

How about listing all elements of a particular group, say for ‘AC Gilchrist’

Image for post

Group by column and apply aggregate

So far we have learned how to create a group, next we can calculate some aggregated stats of each group.python-group-by

To calculate specific aggregate function on columns pass the dictionary of column names with aggregate functions.

Image for post

Group by single column and apply lambda expression

pass a dictionary of column as keys and values as a lambda function

Image for post

Group by multiple column and apply aggregate