Pandas – Group the Data

In this lesson, we will learn how to group data in a DataFrame and perform operations on it. First, we will split the data into groups, then we will iterate through the groups and then display the groups. Let us see what we will cover:

  • Split the object and combine the result
  • Iterate the Group
  • View the Group
  • Perform Aggregation Operations on Groups

Pandas – Split the object and combine the result

The groupby() method is used in Pandas to split the object. We can define groupby() as grouping the rows/columns into specific groups. In the below example, we are grouping by the Player column:

Output

Iterate the Group

Iterate and loop through the groups with groupby() using the for-in loop. In the below example, the iteration is through the group Player one by one:

Output

View the Group

Use the groups property in Python Pandas to view the group. Let us see an example:

Output

Aggregation Operation on Groups

After grouping, we can perform operations on the grouped data using the agg() method. Through this method, get the mean or even get the size of each group, etc. Let’s see some examples:

  • Get the mean of the grouped data
  • Get the size of each group

Get the mean of the grouped data

To get the mean of the grouped data, first, group and then use the agg() method with numpy.mean(). Let us see an example:

Output

Get the size of each group

To get the size of each group, use the Numpy size attribute in Pandas. We have grouped by the Player column using the groupby(). Let us see an example:

Output

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:


For Videos, Join Our YouTube Channel: Join Now


Read More:

Pandas - Cleaning the Data
Pandas - Statistical Functions
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading