GroupBy and Apply multiple Aggregations with named functions in Pandas
Pandas Advanced Grouping and Aggregation: Exercise-15 with Solution
GroupBy and Applying Multiple Aggregations with Named Functions:
Write a Pandas program to apply multiple aggregations with named functions in GroupBy for detailed data analysis.
Sample Solution:
Python Code :
import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value1': [5, 10, 15, 20, 25, 30],
'Value2': [50, 100, 150, 200, 250, 300]}
df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and apply multiple named aggregations
print("\nGroup by 'Category' and apply multiple named aggregations:")
grouped = df.groupby('Category').agg(
Total_Value1=('Value1', 'sum'),
Average_Value2=('Value2', 'mean')
)
print(grouped)
Output:
Sample DataFrame: Category Value1 Value2 0 A 5 50 1 A 10 100 2 B 15 150 3 B 20 200 4 C 25 250 5 C 30 300 Group by 'Category' and apply multiple named aggregations: Total_Value1 Average_Value2 Category A 15 75.0 B 35 175.0 C 55 275.0
Explanation:
- Import pandas.
- Create a sample DataFrame.
- Group by 'Category'.
- Apply multiple named aggregations: sum for 'Value1' and mean for 'Value2'.
- Print the result.
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.
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://198.211.115.131/python-exercises/pandas/advanced-grouping-and-aggregation/groupby-and-apply-multiple-aggregations-with-named-functions-in-pandas.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics