agg() 메서드
agg()로 여러 집계 함수를 한 번에 적용하고, 딕셔너리를 전달해 열마다 다른 통계를 계산합니다.
agg() 메서드은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“agg() 메서드”에서 뭘 배우나요?
agg()로 여러 집계 함수를 한 번에 적용하고, 딕셔너리를 전달해 열마다 다른 통계를 계산합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“agg() 메서드” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.