0Pricing
Pandas & NumPy Academy · 课时

拆分—应用—合并模式

理解 groupby 的概念流程:将 DataFrame 拆分为多个组,应用函数,再合并结果。

拆分—应用—合并模式 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

常见问题解答

「拆分—应用—合并模式」课时是免费的吗?

是的 — 「拆分—应用—合并模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。

「拆分—应用—合并模式」这节课中我会学到什么?

理解 groupby 的概念流程:将 DataFrame 拆分为多个组,应用函数,再合并结果。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Pandas & NumPy Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「拆分—应用—合并模式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?

能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 拆分—应用—合并模式
  2. 使用单个和多个键进行 GroupBy
  3. agg() 方法
  4. GroupBy 变换与筛选
← 返回 Pandas & NumPy Academy