w3resource

Apply Multiple Aggregations on Grouped Data in Pandas

Pandas Advanced Grouping and Aggregation: Exercise-2 with Solution

Applying Multiple Aggregations:
Write a Pandas program to apply multiple aggregation functions to grouped data using for enhanced data insights.

Sample Solution:

Python Code :

import pandas as pd

# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
        'Value': [10, 20, 30, 40, 50, 60]}

df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)

# Group by 'Category' and apply multiple aggregations
print("\nGroup by 'Category' and apply multiple aggregations:")
grouped = df.groupby('Category').agg(['sum', 'mean', 'max'])

print(grouped)

Output:

Sample DataFrame:
  Category  Value
0        A     10
1        A     20
2        B     30
3        B     40
4        C     50
5        C     60

Group by 'Category' and apply multiple aggregations:
           Value          
           sum  mean max
Category                
A           30  15.0  20
B           70  35.0  40
C          110  55.0  60

Explanation:

  • Import pandas.
  • Create a sample DataFrame.
  • Group by 'Category'.
  • Apply sum, mean, and max aggregations.
  • Print the result.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Group by Multiple columns in Pandas.
Next: Use Custom Aggregation Functions in Pandas GroupBy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/advanced-grouping-and-aggregation/apply-multiple-aggregations-on-grouped-data-in-pandas.php