The agg() Method
Apply multiple aggregation functions at once with agg(), pass a dict to compute different stats for different columns.
The agg() Method is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Use agg()?
Calling sum() or mean() directly on a GroupBy object gives you a single statistic. But real analyses often need multiple statistics at once — for example, the total revenue, average order size, and order count per region. The agg() method (short for aggregate) lets you compute all of these in a single, efficient call instead of running separate aggregations and merging results.
Passing a List of Function Names
The simplest use of agg() is to pass a list of function name strings. Pandas applies every function to the selected column and returns a DataFrame where each column corresponds to one function. This approach works with any built-in aggregation name: 'sum', 'mean', 'min', 'max', 'count', 'std', 'median', and others.
import pandas as pd
df = pd.DataFrame({
'region': ['East', 'West', 'East', 'West', 'East', 'West'],
'revenue': [200, 340, 150, 290, 310, 410],
'units': [20, 35, 15, 30, 28, 40]
})
result = df.groupby('region')['revenue'].agg(['sum', 'mean', 'count', 'max'])
print(result)
# sum mean count max
# region
# East 660 220.000000 3 310
# West 1040 346.666667 3 410Renaming Output Columns with Named Aggregations
When you pass a list of strings, the output columns are named after the functions themselves ('sum', 'mean' etc.). For cleaner output, use named aggregations: pass keyword arguments where the key is your desired column name and the value is a tuple of (column, function). This is the modern Pandas approach and produces self-documenting code.
result = df.groupby('region').agg(
total_revenue=('revenue', 'sum'),
avg_revenue=('revenue', 'mean'),
order_count=('revenue', 'count'),
max_order=('revenue', 'max')
)
print(result)
# total_revenue avg_revenue order_count max_order
# region
# East 660 220.000000 3 310
# West 1040 346.666667 3 410Different Functions for Different Columns
You can pass a dictionary to agg() where each key is a column name and each value is a function (or list of functions) to apply to that column. This lets you compute, for example, sum on revenue but mean on units, all in a single GroupBy call.
result = df.groupby('region').agg({
'revenue': ['sum', 'mean'],
'units': ['sum', 'max']
})
print(result)
# revenue units
# sum mean sum max
# region
# East 660 220.000000 63 28
# West 1040 346.666667 105 40Column MultiIndex from Dict agg()
When you pass a dict with multiple functions per column, the result has a MultiIndex on columns. The first level is the original column name and the second level is the function name. You can flatten these column names into a single string with a list comprehension, making the result easier to work with downstream.
result = df.groupby('region').agg({'revenue': ['sum', 'mean'], 'units': 'sum'})
# Flatten MultiIndex columns
result.columns = ['_'.join(c).strip() for c in result.columns]
print(result.columns.tolist())
# ['revenue_sum', 'revenue_mean', 'units_sum']Using Custom Functions in agg()
In addition to string names, you can pass any Python callable to agg(). The function receives a Series (the values for that column in one group) and must return a scalar. You can pass a lambda or a named function. Custom functions are more flexible but slower than built-in named functions because they cannot use the C-level optimisations.
def revenue_range(s):
return s.max() - s.min()
result = df.groupby('region')['revenue'].agg(['sum', revenue_range])
print(result)
# sum revenue_range
# region
# East 660 160
# West 1040 120Named Aggregations with Custom Functions
Named aggregation syntax also works with callable functions, not just string names. Simply pass a tuple of (column, function) as the keyword argument value, where the function is any callable that accepts a Series and returns a scalar. This keeps your code readable even when mixing built-ins with custom logic.
result = df.groupby('region').agg(
total=('revenue', 'sum'),
spread=('revenue', lambda s: s.max() - s.min()),
top_units=('units', 'max')
)
print(result)
# total spread top_units
# region
# East 660 160 28
# West 1040 120 40Aggregating Without Selecting a Column
When you call agg() on a GroupBy without selecting a specific column, Pandas applies the function to every numeric column in the DataFrame. This is a quick way to get a summary of all numeric columns at once. Be aware that columns with non-numeric data types will be silently skipped in most aggregations.
# Aggregate all numeric columns in one call
result = df.groupby('region').agg(['sum', 'mean'])
print(result)
# revenue units
# sum mean sum mean
# region
# East 660 220.000000 63 21.00
# West 1040 346.666667 105 35.00Combining agg() with reset_index()
After agg(), the grouping column(s) are the index. A common pattern is to call reset_index() immediately to get a flat DataFrame where the group keys are regular columns. You can then rename, sort, and filter the result like any other DataFrame, making it easy to pass downstream or export.
summary = (
df.groupby('region')
.agg(total=('revenue', 'sum'), orders=('revenue', 'count'))
.reset_index()
.sort_values('total', ascending=False)
)
print(summary)
# region total orders
# 1 West 1040 3
# 0 East 660 3agg() vs transform() vs apply()
It is important to distinguish three GroupBy methods: agg() reduces each group to a scalar, producing a result with fewer rows than the original. transform() returns an array with the same shape as the input, so you can add group-level statistics as new columns. apply() is the most flexible but also the slowest, and is covered in the next lesson.
# agg: one row per group
print(df.groupby('region')['revenue'].agg('mean'))
# region
# East 220.0
# West 346.7
# transform: one row per original row (group mean broadcast back)
df['group_mean'] = df.groupby('region')['revenue'].transform('mean')
print(df[['region', 'revenue', 'group_mean']].head())Practical Example: Sales Summary
Here is a realistic end-to-end example: compute a sales summary table with total revenue, average order value, number of orders, and the revenue range per region, with clean column names, sorted by total revenue descending. This pattern is directly applicable in product, finance, and marketing analytics workflows.
summary = (
df.groupby('region')
.agg(
total_revenue=('revenue', 'sum'),
avg_order=('revenue', 'mean'),
num_orders=('revenue', 'count'),
revenue_range=('revenue', lambda s: s.max() - s.min())
)
.reset_index()
.sort_values('total_revenue', ascending=False)
.round(2)
)
print(summary)Quick Check
Test your understanding of the agg() method from this lesson.
Lesson Recap
In this lesson you learned: how to compute multiple aggregations at once with agg(), how to use named aggregations for clean column names, and how to apply different functions to different columns using a dict. Next up we explore transform() and filter(), which add group-level information back to the original DataFrame.
Frequently asked questions
Is the “The agg() Method” lesson free?
Yes — the full text of “The agg() Method” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “The agg() Method”?
Apply multiple aggregation functions at once with agg(), pass a dict to compute different stats for different columns. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The agg() Method” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.