GroupBy: Split-Apply-Combine

Reviewed & published by Brayan K

GroupBy in pandas is the operation that splits a DataFrame into groups by the values in one or more key columns, applies a summary function such as mean or sum to each group, and combines the answers into one tidy result.

Part of the free Pandas course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Learn the split-apply-combine pattern, group by single and multiple keys, run common aggregations, iterate groups, and reach into a specific group with get_group.

What You'll Learn in This Lesson

1 Split-Apply-Combine in Action

Every groupby follows three steps. Split the rows into groups by a key, apply a function to each group, then combine the results. The pattern df.groupby("key")["value"].mean() reads exactly like that sentence.

import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "South", "North"],
    "product": ["A", "A", "B", "B", "A"],
    "amount": [100, 80, 50, 90, 120],
})

# Average amount per region
print(sales.groupby("region")["amount"].mean())
# North -> 90.0, South -> 85.0

# Total and count per region
print(sales.groupby("region")["amount"].sum())    # North 270, South 170
print(sales.groupby("region")["amount"].count())  # North 3, South 2

# ✅ Expected output:
# region
# North    90.0
# South    85.0
# Name: amount, dtype: float64
# region
# North    270
# South    170
# Name: amount, dtype: int64
# region
# North    3
# South    2
# Name: amount, dtype: int64

2 Multiple Keys and .agg()

Group by several columns by passing a list, which forms a group for every unique combination and produces a MultiIndex result. The .agg() method lets you run more than one function at once, returning a column for each.

import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "South", "North"],
    "product": ["A", "A", "B", "B", "A"],
    "amount": [100, 80, 50, 90, 120],
})

# Group by TWO keys -> a result per region+product combination
print(sales.groupby(["region", "product"])["amount"].sum())

# Several aggregations at once with .agg()
print(sales.groupby("region")["amount"].agg(["sum", "mean", "max"]))
#         sum   mean  max
# North   270   90.0  120
# South   170   85.0   90

# ✅ Expected output:
# region  product
# North   A          220
#         B           50
# South   A           80
#         B           90
# Name: amount, dtype: int64
#         sum  mean  max
# region                
# North   270  90.0  120
# South   170  85.0   90

3 Iterating Groups, get_group, and as_index

A groupby object is iterable: each loop gives you the group key and its DataFrame slice. get_group() jumps straight to one group, and as_index=False keeps the grouping keys as ordinary columns instead of moving them into the index.

import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "South"],
    "amount": [100, 80, 50, 90],
})

grouped = sales.groupby("region")

# Iterate: key + the sub-DataFrame for that group
for key, sub in grouped:
    print(key, "has", len(sub), "rows, total", sub["amount"].sum())

# Jump to a single group
print(grouped.get_group("North"))

# as_index=False keeps 'region' as a normal column
print(sales.groupby("region", as_index=False)["amount"].sum())
#   region  amount
# 0  North     150
# 1  South     170

# ✅ Expected output:
# North has 2 rows, total 150
# South has 2 rows, total 170
#   region  amount
# 0  North     100
# 2  North      50
#   region  amount
# 0  North     150
# 1  South     170

🎯 Your Turn: Sales per Region

Replace the blank so you total the amount for each region. The expected output is North 270 and South 170.

import pandas as pd

df = pd.DataFrame({
    "region": ["North", "South", "North", "South", "North"],
    "amount": [100, 80, 50, 90, 120],
})

# 🎯 YOUR TURN: group by 'region' and total the 'amount'
totals = df.groupby("___")["amount"].sum()
print(totals)

# Expected output: North -> 270, South -> 170

📋 Quick Reference

TaskCode
Mean per groupdf.groupby("k")["v"].mean()
Multiple keysdf.groupby(["a", "b"])["v"].sum()
Several functionsg["v"].agg(["sum", "mean"])
One groupg.get_group("North")
Keys as columnsdf.groupby("k", as_index=False)

🎯 Mini Challenge: Store Report

Build a per-store report: total sales, average sale, and number of transactions, with the store kept as a column.

import pandas as pd

df = pd.DataFrame({
    "store": ["A", "B", "A", "B", "A"],
    "category": ["food", "food", "toys", "toys", "food"],
    "sales": [40, 25, 60, 30, 55],
})

# Total, average, and count of sales for each store, store as a column
report = (df.groupby("store", as_index=False)["sales"]
            .agg(["sum", "mean", "count"]))
print(report)

# Bonus: total sales per store AND category combination
print(df.groupby(["store", "category"])["sales"].sum())

# ✅ Expected output:
#   store  sum       mean  count
# 0     A  155  51.666667      3
# 1     B   55  27.500000      2
# store  category
# A      food        95
#        toys        60
# B      food        25
#        toys        30
# Name: sales, dtype: int64

❓ Frequently Asked Questions

Lesson complete — you can summarise by category!

You now understand split-apply-combine, can group by one or many keys, run mean, sum and count, apply several functions with agg, iterate groups, reach into one with get_group, and flatten results with as_index=False.

Practice quiz

What are the three steps of the split-apply-combine pattern?

  • Load, clean, save
  • Sort, filter, join
  • Split into groups, apply a function, combine results
  • Map, reduce, shuffle

Answer: Split into groups, apply a function, combine results. groupby splits rows into groups, applies a function to each, then combines the results.

What does df.groupby('region')['amount'].mean() compute?

  • The overall mean of amount
  • The mean amount within each region
  • A count per region
  • The maximum amount

Answer: The mean amount within each region. It splits by region and averages amount within each group.

How do you group by more than one column?

  • Call groupby twice
  • Use groupby('a+b')
  • Pass a list, e.g. groupby(['region','product'])
  • Use groupby with sum only

Answer: Pass a list, e.g. groupby(['region','product']). Pass a list of column names to form a group per unique combination.

What does grouping by multiple keys produce in the result?

  • A flat single index
  • A MultiIndex, one level per key
  • A new column
  • An error

Answer: A MultiIndex, one level per key. Multiple grouping keys give a MultiIndex with one level per key.

Which method runs several aggregation functions at once?

  • .agg(['sum','mean','max'])
  • .apply_all()
  • .multi()
  • .describe_each()

Answer: .agg(['sum','mean','max']). .agg([...]) returns a column for each function you pass.

What does as_index=False do?

  • Drops the grouping keys
  • Sorts the groups
  • Reverses the order
  • Keeps the grouping keys as ordinary columns

Answer: Keeps the grouping keys as ordinary columns. as_index=False keeps the keys as columns instead of moving them into the index.

What does grouped.get_group('North') return?

  • The mean of North
  • Just the North sub-DataFrame
  • A boolean mask
  • The number of groups

Answer: Just the North sub-DataFrame. get_group jumps straight to the rows of a single named group.

For amounts North [100,50,120] and South [80,90], what is the sum for North?

  • 170
  • 85.0
  • 270
  • 90.0

Answer: 270. 100 + 50 + 120 = 270 for North.

When you iterate a groupby object, what does each loop give you?

  • The group key and its sub-DataFrame
  • Only the key
  • Only the values
  • A single number

Answer: The group key and its sub-DataFrame. Iterating yields a (key, sub-DataFrame) pair for each group.

as_index=False is essentially equivalent to what afterwards?

  • sort_values()
  • drop_duplicates()
  • set_index()
  • reset_index()

Answer: reset_index(). Both flatten the grouping keys back into columns; reset_index does it after the fact.

Continue this course

Frequently asked questions

What is split-apply-combine in pandas?

Split-apply-combine is the mental model behind groupby. Pandas first splits the rows into groups based on a key column, then applies a function such as mean or sum to each group, and finally combines the per-group results into a single output Series or DataFrame.

How do I group by more than one column in pandas?

Pass a list of column names, for example df.groupby(['region', 'product']). Pandas forms a group for every unique combination of those columns and returns a result with a MultiIndex, one level per grouping key.

What does as_index=False do in groupby?

By default the grouping keys become the index of the result. Passing as_index=False keeps them as ordinary columns instead, which gives you a flat DataFrame that is easier to merge or export. It is equivalent to calling reset_index afterwards.