We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Custom Aggregations

Built-in functions like sum and mean cover most cases, but sometimes you need a calculation that doesn't exist out-of-the-box, like a revenue range. Luckily, you can pass custom functions to .agg() using lambda functions or regular ol' named functions.

orders = pd.DataFrame(
    {
        "category": ["Electronics", "Electronics", "Clothing", "Clothing", "Clothing"],
        "revenue": [500, 100, 200, 400, 350],
        "cost": [300, 60, 100, 200, 175],
    }
)

summary = orders.groupby("category").agg(
    revenue_range=("revenue", lambda x: x.max() - x.min()),
)

You can also just define a regular named function, and pass it in:

def revenue_range(series):
    return series.max() - series.min()


summary = orders.groupby("category").agg(
    spread=("revenue", revenue_range),
)

If your lambda is longer than one line of logic, write a named function instead. Named functions are easier to test and debug.

Mixing Custom and Built-in Functions

There's nothing wrong with using custom functions and built-in ones in the same .agg() call:

summary = orders.groupby("category").agg(
    total_revenue=("revenue", "sum"),
    order_count=("revenue", "count"),
    revenue_spread=("revenue", lambda x: x.max() - x.min()),
)

Assignment

SnackStack's reliability team watches for ovens and fridges whose temperature bounces around too much.