Use Custom Aggregation Functions in Pandas GroupBy
3. Custom Aggregation Functions
Write a Pandas program to implement custom aggregation functions within groupby for tailored data analysis.
Sample Solution:
Python Code :
import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value': [5, 15, 25, 35, 45, 55]}
df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Define custom aggregation function
def custom_agg(x):
return x.max() - x.min()
# Group by 'Category' and apply custom aggregation
print("\nGroup by 'Category' and apply custom aggregation:")
grouped = df.groupby('Category').agg(custom_agg)
print(grouped)
Output:
Sample DataFrame:
Category Value
0 A 5
1 A 15
2 B 25
3 B 35
4 C 45
5 C 55
Group by 'Category' and apply custom aggregation:
Value
Category
A 10
B 10
C 10
Explanation:
- Import pandas.
- Create a sample DataFrame.
- Define a custom aggregation function.
- Group by 'Category' and apply the custom function.
- Print the result.
For more Practice: Solve these Related Problems:
- Write a Pandas program to group data and apply a custom function that calculates the range (max-min) for each group.
- Write a Pandas program to implement a custom aggregation that returns the second highest value within each group.
- Write a Pandas program to group data and apply a custom lambda function that computes a weighted average for a specified column.
- Write a Pandas program to group data and apply a custom aggregation function that outputs multiple statistics as a tuple.
Go to:
PREV : Applying Multiple Aggregations.
NEXT : Group by and Filter Groups.
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.
