0Pricing
Pandas & NumPy Academy · Lesson

The Split-Apply-Combine Pattern

Understand the conceptual flow of groupby: splitting the DataFrame into groups, applying a function, and combining results.

The Split-Apply-Combine Pattern is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “The Split-Apply-Combine Pattern” lesson free?

Yes — the full text of “The Split-Apply-Combine Pattern” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “The Split-Apply-Combine Pattern”?

Understand the conceptual flow of groupby: splitting the DataFrame into groups, applying a function, and combining results. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “The Split-Apply-Combine Pattern” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Split-Apply-Combine Pattern
  2. GroupBy with Single and Multiple Keys
  3. The agg() Method
  4. GroupBy Transform and Filter
← Back to Pandas & NumPy Academy