Aggregate with different functions on different columns in Pandas
Pandas Advanced Grouping and Aggregation: Exercise-6 with Solution
Aggregating with different functions on different Columns:
Write a Pandas program to use different aggregation functions on different columns for versatile data analysis.
Sample Solution:
Python Code :
import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value1': [1, 2, 3, 4, 5, 6],
'Value2': [10, 20, 30, 40, 50, 60]}
df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and apply different aggregations
print("\nGroup by 'Category' and apply different aggregations:")
grouped = df.groupby('Category').agg({'Value1': 'sum', 'Value2': 'mean'})
print(grouped)
Output:
Sample DataFrame: Category Value1 Value2 0 A 1 10 1 A 2 20 2 B 3 30 3 B 4 40 4 C 5 50 5 C 6 60 Group by 'Category' and apply different aggregations: Value1 Value2 Category A 3 15.0 B 7 35.0 C 11 55.0
Explanation:
- Import pandas.
- Create a sample DataFrame.
- Group by 'Category'.
- Apply sum aggregation on 'Value1' and mean aggregation on 'Value2'.
- Print the result.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Group by and Apply function to Groups in Pandas.
Next: Using GroupBy with Lambda functions in Pandas.
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/aggregate-with-different-functions-on-different-columns-in-pandas.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics