0Pricing
Pandas & NumPy Academy · 강의

분할-적용-결합 패턴

groupby의 개념적 흐름인 DataFrame 분할, 함수 적용, 결과 결합을 이해합니다.

분할-적용-결합 패턴은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is GroupBy?

The GroupBy operation is one of the most powerful patterns in data analysis. It lets you split a DataFrame into groups, apply a function to each group independently, and then combine the results into a new structure. This workflow is known as the split-apply-combine pattern, a term coined by statistician Hadley Wickham.

The Split Step

In the split step, Pandas divides the DataFrame into sub-DataFrames based on the unique values in one or more columns. For example, if your data has a region column with values like 'North', 'South', and 'West', the split step creates three separate groups. No data is moved or copied yet — Pandas just records which rows belong to which group.

import pandas as pd

df = pd.DataFrame({
    'region': ['North', 'South', 'North', 'West', 'South'],
    'sales': [200, 150, 300, 180, 220]
})

# split: create a GroupBy object
grouped = df.groupby('region')
print(type(grouped))  # DataFrameGroupBy

The Apply Step

In the apply step, a function is applied to each group independently. The function can be a built-in aggregation like sum() or mean(), or a custom function you define. Each group's rows are passed to the function, and it returns a scalar, a Series, or a DataFrame as the result.

# apply: compute the sum of 'sales' within each region group
total_sales = grouped['sales'].sum()
print(total_sales)
# region
# North    500
# South    370
# West     180
# Name: sales, dtype: int64

The Combine Step

In the combine step, Pandas automatically assembles the per-group results back into a single object — typically a Series or DataFrame. The group keys become the index of the result. This step happens invisibly when you call an aggregation method on a GroupBy object, giving you a clean summary table with one row per group.

# combine happens automatically — result is a Series indexed by 'region'
print(total_sales.index)   # Index(['North', 'South', 'West'])
print(total_sales.values)  # [500, 370, 180]

Creating a GroupBy Object

You create a GroupBy object by calling df.groupby(column). Nothing is computed at this stage — it is a lazy object. You can iterate over it to see the groups, or chain an aggregation method to trigger computation. Passing as_index=False keeps the grouping column as a regular column instead of the index in the result.

grouped = df.groupby('region', as_index=False)
result = grouped['sales'].sum()
print(result)
#   region  sales
# 0  North    500
# 1  South    370
# 2   West    180

Iterating Over Groups

You can iterate over a GroupBy object to inspect each group individually. Each iteration yields a tuple of (group_key, sub_dataframe). This is useful for debugging or when you want to process each group with arbitrary Python code. However, for performance in production, prefer vectorised aggregation methods over explicit iteration.

for name, group in df.groupby('region'):
    print(f'--- {name} ---')
    print(group)
# --- North ---
#   region  sales
# 0  North    200
# 2  North    300
# --- South ---
#   region  sales
# 1  South    150
# 4  South    220

Common Aggregation Functions

Pandas GroupBy supports many built-in aggregation functions: sum(), mean(), count(), min(), max(), std(), median(), and more. These are highly optimised and run on all groups in a single pass. Always prefer them over writing a custom Python function when the built-in exists.

print(df.groupby('region')['sales'].mean())
# region
# North    250.0
# South    185.0
# West     180.0

print(df.groupby('region')['sales'].count())
# region
# North    2
# South    2
# West     1

Grouping Multiple Columns at Once

You can apply aggregations to multiple columns simultaneously by selecting them before calling the aggregation method, or by omitting column selection to aggregate all numeric columns. The result is a DataFrame instead of a Series, with one column per aggregated variable.

df2 = pd.DataFrame({
    'region': ['North', 'South', 'North', 'South'],
    'units': [10, 8, 12, 9],
    'revenue': [200, 160, 240, 180]
})

print(df2.groupby('region').sum())
#         units  revenue
# region
# North      22      440
# South      17      340

The GroupBy Mental Model

Think of GroupBy like SQL's GROUP BY clause. The Pandas code df.groupby('region')['sales'].sum() is equivalent to SELECT region, SUM(sales) FROM df GROUP BY region in SQL. Understanding this parallel helps you translate between the two tools and choose the right abstraction for your pipeline.

# Pandas GroupBy is equivalent to SQL GROUP BY
# SQL:    SELECT region, SUM(sales) FROM df GROUP BY region
# Pandas: df.groupby('region')['sales'].sum()

result = df.groupby('region')['sales'].sum().reset_index()
result.columns = ['region', 'total_sales']
print(result)

Why Not Use a Loop Instead?

You might wonder why not just loop over unique values and compute statistics manually. The answer is performance and readability. A Python loop over groups is much slower than a single vectorised groupby call, especially for large datasets. GroupBy operations run in compiled C code internally, making them 10-100x faster than equivalent Python loops.

# Slow approach with a loop
results = {}
for region in df['region'].unique():
    subset = df[df['region'] == region]
    results[region] = subset['sales'].sum()

# Fast approach with GroupBy
results_fast = df.groupby('region')['sales'].sum().to_dict()
# Both give the same answer, but GroupBy is orders of magnitude faster

GroupBy With Multiple Group Keys

When you need finer granularity, group by multiple columns by passing a list to groupby(). The result has a MultiIndex where each level corresponds to one grouping column. For example, grouping by both 'region' and 'quarter' gives totals for every region-quarter combination.

df3 = pd.DataFrame({
    'region': ['North', 'North', 'South', 'South'],
    'quarter': ['Q1', 'Q2', 'Q1', 'Q2'],
    'sales': [200, 300, 150, 220]
})

print(df3.groupby(['region', 'quarter'])['sales'].sum())
# region  quarter
# North   Q1         200
#         Q2         300
# South   Q1         150
#         Q2         220

Quick Check

Test your understanding of the split-apply-combine pattern from this lesson.

Lesson Recap

In this lesson you learned: the split-apply-combine pattern that underlies all GroupBy operations, how to create a GroupBy object with df.groupby(), and how to apply built-in aggregations like sum() and mean() to get one result per group. Next up we explore grouping by single and multiple keys with more aggregation methods.

자주 묻는 질문

“분할-적용-결합 패턴” 강의는 무료인가요?

네 — “분할-적용-결합 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“분할-적용-결합 패턴”에서 뭘 배우나요?

groupby의 개념적 흐름인 DataFrame 분할, 함수 적용, 결과 결합을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“분할-적용-결합 패턴” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 분할-적용-결합 패턴
  2. 단일 키와 여러 키를 사용한 GroupBy
  3. agg() 메서드
  4. GroupBy 변환과 필터링
← Pandas & NumPy Academy(으)로 돌아가기