0Pricing
Pandas & NumPy Academy · Урок

Шаблон «разделить — применить — объединить»

Разберитесь в концептуальном ходе groupby: разделении DataFrame на группы, применении функции и объединении результатов.

«Шаблон «разделить — применить — объединить»» — бесплатный урок Pandas & NumPy Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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) и разблокировать остальной курс Pandas & NumPy Academy, подпишись на CoddyKit PRO. Курс Pandas & NumPy Academy содержит 4 уроков всего.

Чему я научусь в уроке «Шаблон «разделить — применить — объединить»»?

Разберитесь в концептуальном ходе groupby: разделении DataFrame на группы, применении функции и объединении результатов. Ты практикуешь Pandas & NumPy Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Pandas & NumPy Academy?

Предыдущий опыт не требуется. Pandas & NumPy Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Шаблон «разделить — применить — объединить»»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Pandas & NumPy Academy?

Да. Каждый урок Pandas & NumPy Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Шаблон «разделить — применить — объединить»
  2. GroupBy с одним и несколькими ключами
  3. Метод agg()
  4. Преобразование и фильтрация GroupBy
← Назад к Pandas & NumPy Academy