Apply Multiple Aggregations on Grouped Data in Pandas
2. 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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to group a DataFrame by a column and apply multiple aggregations (min, max, mean) on different numeric columns.
- Write a Pandas program to apply a list of aggregation functions on grouped data and then rename the aggregated columns for clarity.
- Write a Pandas program to group data and simultaneously calculate the standard deviation and variance for a given numeric column.
- Write a Pandas program to group a dataset and use custom aggregations alongside built-in functions on different columns.
Go to:
PREV : Grouping by Multiple columns.
NEXT : Custom Aggregation Functions.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
