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

Named Aggregations

Passing a list to .agg() names the output columns after the functions themselves: sum, mean, max. That's fine for a quick look, but a realtm report has descriptive names, and sometimes the stats you need come from different columns. Named aggregations solve both problems at once.

Use keyword arguments inside .agg(), where each keyword is the output column name and its value is a tuple of (source_column, function):

orders = pd.DataFrame(
    {
        "category": ["Electronics", "Electronics", "Clothing", "Clothing"],
        "revenue": [500, 300, 200, 400],
        "quantity": [1, 2, 3, 1],
    }
)

summary = orders.groupby("category").agg(
    total_revenue=("revenue", "sum"),
    avg_revenue=("revenue", "mean"),
    total_units=("quantity", "sum"),
    order_count=("revenue", "count"),
)
print(summary)
#              total_revenue  avg_revenue  total_units  order_count
# category
# Clothing               600        300.0            4            2
# Electronics            800        400.0            3            2

Every output column has exactly the name you gave it, and the four columns pull from two different source columns in a single call.

Assignment

SnackStack's operations team wants a tidy per-region scorecard for the fleet dashboard, with clean column names they don't have to rename by hand.

Complete the summarize_devices_by_region function. It accepts a DataFrame with region, device_id, temperature_celsius, and energy_kwh columns and returns one summary row per region.

    • device_count: the number of unique device_id values
    • avg_temperature: the mean temperature_celsius
    • total_energy: the sum of energy_kwh