Pandas - Grouping and aggregating DataFrame with a custom function using apply()
19. Aggregate DataFrame Groups with a Custom Function
Write a Pandas program that applies a custom function to aggregate DataFrame groups.
In this exercise, we have grouped a DataFrame by a specific column and apply a custom aggregation function using apply().
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'Category': ['A', 'B', 'A', 'B'],
'Value': [10, 20, 15, 25]
})
# Define a custom aggregation function
def custom_agg(group):
return group['Value'].sum()
# Group by 'Category' and apply the custom aggregation function
df_grouped = df.groupby('Category').apply(custom_agg)
# Output the result
print(df_grouped)
Output:
Category A 25 B 45 dtype: int64
Explanation:
- Created a DataFrame with a 'Category' and 'Value' column.
- Defined a custom aggregation function custom_agg() to calculate the sum of values in each group.
- Grouped the DataFrame by 'Category' and applied the custom aggregation using apply().
- Returned the summed values for each group.
For more Practice: Solve these Related Problems:
- Write a Pandas program to group a DataFrame by a specific column and then use apply() to aggregate each group with a custom function.
- Write a Pandas program to create a custom aggregation function and apply it to each group using groupby() and apply().
- Write a Pandas program to compute multiple group-level statistics by applying a custom function to each group via apply().
- Write a Pandas program to compare the output of a custom aggregation function applied via apply() with built-in groupby aggregation methods.
Python-Pandas 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.