How to combine Groupby and Multiple Aggregate Functions in Pandas?

Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. It is an open-source library that is built on top of NumPy library.

Groupby()

Pandas dataframe.groupby() function is used to split the data in dataframe into groups based on a given condition.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# import library
import pandas as pd
  
# import csv file
df = pd.read_csv("https://bit.ly/drinksbycountry")
  
df.head()

chevron_right


Output:

Example 2:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Find the average of each continent
# by grouping the data  
# based on the "continent".
df.groupby(["continent"]).mean()

chevron_right


Output:

Aggregate()

Pandas dataframe.agg() function is used to do one or more operations on data based on specified axis

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# here sum, minimum and maximum of column 
# beer_servings is calculatad
df.beer_servings.agg(["sum", "min", "max"])

chevron_right


Output:

Using These two functions together: We can find multiple aggregation functions of a particular column grouped by another column.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# find an aggregation of column "beer_servings"
# by grouping the "continent" column.
df.groupby(df["continent"]).beer_servings.agg(["min",
                                               "max",
                                               "sum",
                                               "count",
                                               "mean"])

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.