Course contentsShow
← Python
Lesson 955 of 1,06015. Data Science FundamentalsFree lesson

Performing Custom Aggregations on Groups

Apply multiple custom mathematical and statistical functions simultaneously to grouped data to generate comprehensive descriptive summaries.

In this lesson, you will learn how to extract comprehensive statistical insights by applying multiple, distinct mathematical functions to your grouped data simultaneously.

Moving Beyond Simple Aggregates

While standard functions like sum() or mean() are useful, real-world data science often requires a richer descriptive summary. When you use the groupby object's .agg() method, you aren't restricted to a single operation. Instead, you can pass a list or dictionary of functions to generate a multi-dimensional view of your data in one pass.

Applying Multiple Functions

To perform custom aggregations, pass a list of functions—either string aliases (like 'min', 'max') or custom Python functions—to the .agg() method. This allows you to inspect the distribution, variance, and central tendency of a group simultaneously.

Consider a dataset of sales records grouped by Region. If we want to see both the range (difference between max and min) and the standard deviation for each region, we can define a custom function and combine it with built-in ones:

import numpy as np

# Define a custom function for range
def get_range(x):
    return x.max() - x.min()

# Apply multiple functions to the 'Sales' column
summary = df.groupby('Region')['Sales'].agg(['mean', 'std', get_range])

print(summary)

Targeted Column Aggregations

For more granular control, you can pass a dictionary to .agg(). This allows you to apply different sets of calculations to different columns depending on their nature. For instance, you might want the sum and mean for a Revenue column, but only the median for a Customer_Age column:

summary = df.groupby('Region').agg({
    'Revenue': ['sum', 'mean'],
    'Customer_Age': 'median'
})

By providing a dictionary, you map specific columns to specific transformations. The result is a clean, hierarchical DataFrame that keeps your data organized by the grouping key while providing a high-density summary of your metrics. This technique is essential for quickly identifying patterns or anomalies that wouldn't be visible using only a single summary statistic.

Key Takeaway: Use the .agg() method with lists or dictionaries to compute diverse, multi-functional descriptive statistics across your grouped data in a single, efficient operation.