Метод agg()
Применяйте несколько агрегирующих функций одновременно с помощью agg(), передавая словарь для вычисления разных показателей по разным столбцам.
«Метод agg()» — бесплатный урок Pandas & NumPy Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Pandas & NumPy Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Часто задаваемые вопросы
Урок «Метод agg()» бесплатный?
Да — полный текст урока «Метод agg()» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Pandas & NumPy Academy, подпишись на CoddyKit PRO. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Чему я научусь в уроке «Метод agg()»?
Применяйте несколько агрегирующих функций одновременно с помощью agg(), передавая словарь для вычисления разных показателей по разным столбцам. Ты практикуешь Pandas & NumPy Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Pandas & NumPy Academy?
Предыдущий опыт не требуется. Pandas & NumPy Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Метод agg()»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Pandas & NumPy Academy?
Да. Каждый урок Pandas & NumPy Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Шаблон «разделить — применить — объединить»
- GroupBy с одним и несколькими ключами
- Метод agg()
- Преобразование и фильтрация GroupBy