w3resource

Use Custom Aggregation Functions in Pandas GroupBy

Pandas Advanced Grouping and Aggregation: Exercise-3 with Solution

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.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Apply Multiple Aggregations on Grouped Data in Pandas.
Next: Group by and Filter Groups in Pandas.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/use-custom-aggregation-functions-in-pandas-groupby.php