Apply different functions to different columns with GroupBy
Pandas Advanced Grouping and Aggregation: Exercise-9 with Solution
Applying different functions to different columns with GroupBy:
Write a Pandas program that applies different functions to different columns in Pandas GroupBy for tailored data analysis.
Sample Solution:
Python Code :
import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value1': [10, 20, 30, 40, 50, 60],
'Value2': [100, 200, 300, 400, 500, 600]}
df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and apply different functions
print("\nGroup by 'Category' and apply different functions:")
grouped = df.groupby('Category').agg({'Value1': 'mean', 'Value2': 'sum'})
print(grouped)
Output:
Sample DataFrame: Category Value1 Value2 0 A 10 100 1 A 20 200 2 B 30 300 3 B 40 400 4 C 50 500 5 C 60 600 Group by 'Category' and apply different functions: Value1 Value2 Category A 15.0 300 B 35.0 700 C 55.0 1100
Explanation:
- Import pandas.
- Create a sample DataFrame.
- Group by 'Category'.
- Apply mean aggregation on 'Value1' and sum aggregation on 'Value2'.
- Print the result.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Grouping and Aggregating with multiple Index Levels in Pandas.
Next: Calculating Percentage change in Resampled data.
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://w3resource.com/python-exercises/pandas/advanced-grouping-and-aggregation/apply-different-functions-to-different-columns-with-groupby.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics