w3resource

Pandas - Grouping and aggregating DataFrame with a custom function using apply()


Pandas: Custom Function Exercise-19 with Solution


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.

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.



Follow us on Facebook and Twitter for latest update.