pandas groupby and merge: Split-Apply-Combine and Joining Tables
Two questions you'll ask of data all the time: how much per group, and how do two tables fit together. groupby as split, apply, combine; merge with inner, left and outer on a tiny shop; and the duplicate key that quietly doubles your totals.
What you will learn
- Summarise a table group by group with groupby, sum, mean and named agg
- Turn a groupby result back into a table with reset_index or as_index=False
- Join two tables with merge and predict the rows for inner, left and outer
- Catch the duplicate-key trap with is_unique and validate, and know when to use concat instead
Before you start
- pandas Series and DataFrames
- pandas data cleaning (NaN)
So far you've worked with one table at a time. But most questions need a summary ("how much has each customer spent?"), and many need two tables ("what's the customer's city for this order?"). This lesson adds both: summarising a table with groupby, and joining tables with merge.
A tiny online shop
The data sits in shop.py, so every file can import it:
import pandas as pd
customers = pd.DataFrame(
[
(1, "Maya", "Lisbon"),
(2, "Omar", "Oslo"),
(3, "Lena", "Lisbon"),
(4, "Ravi", "Lima"),
(5, "Sofia", "Oslo"),
],
columns=["customer_id", "name", "city"],
)
orders = pd.DataFrame(
[
(101, 1, "notebook", 12),
(102, 2, "lamp", 40),
(103, 1, "mug", 8),
(104, 3, "notebook", 12),
(105, 2, "mug", 8),
(106, 1, "lamp", 40),
(107, 9, "mug", 8),
],
columns=["order_id", "customer_id", "item", "amount"],
)
customer_id is in both tables, and that's what connects an order to a person. Keep an eye on two odd things: Ravi and Sofia haven't ordered anything, and order 107 belongs to customer 9, who isn't in the customers table. They'll matter when you join.
Split, apply, combine
Think about a stack of paper receipts. First you sort them into piles, one per customer: that's split. Then you add up each pile: apply. Then you write one line per pile on a clean sheet: combine. That's all groupby does.
from shop import orders
for cid, rows in orders.groupby("customer_id"):
print(cid, list(rows["amount"]), rows["amount"].sum())
1 [12, 8, 40] 60
2 [40, 8] 48
3 [12] 12
9 [8] 8
You won't usually write that loop. pandas does all three steps in one line:
total = orders.groupby("customer_id")["amount"].sum()
print(total)
print(type(total).__name__)
customer_id
1 60
2 48
3 12
9 8
Name: amount, dtype: int64
Series
Read it from the left: groupby is the split, ["amount"] picks the column, sum() is the apply. The customer ids are now the row labels (the index), and the result is a Series, not a table.
mean, and several at once with agg
by_customer = orders.groupby("customer_id")["amount"]
print(by_customer.agg(["count", "sum", "mean"]))
count sum mean
customer_id
1 3 60 20.0
2 2 48 24.0
3 1 12 12.0
9 1 8 8.0
The piles stay the same; only the calculation changes. .mean() alone gives 20.0, 24.0, 12.0 and 8.0 (a mean comes back as a float). agg is short for aggregate: several summaries in one go. You can also name your own columns:
stats = orders.groupby("customer_id").agg(
orders=("order_id", "count"),
spent=("amount", "sum"),
biggest=("amount", "max"),
)
print(stats)
orders spent biggest
customer_id
1 3 60 40
2 2 48 40
3 1 12 12
9 1 8 8
Each line reads like a sentence: spent equals amount with sum. For a report, this is the form to reach for, because the result explains itself.
Why you pick a column
groups = orders.groupby("customer_id")
print(groups.sum())
print(groups.sum(numeric_only=True))
order_id item amount
customer_id
1 310 notebookmuglamp 60
2 207 lampmug 48
3 104 notebook 12
9 107 mug 8
order_id amount
customer_id
1 310 60
2 207 48
3 104 12
9 107 8
Without a column, sum runs on everything it can. Order ids added up mean nothing, and adding text glues it into one word. numeric_only=True removes the text but keeps order_id, because it's a number even though it's really a label. pandas can't tell which numbers make sense to add. You can, so pick the column.
Several keys, and back to a table
pairs = orders.groupby(["customer_id", "item"])["amount"]
print(pairs.sum())
customer_id item
1 lamp 40
mug 8
notebook 12
2 lamp 40
mug 8
3 notebook 12
9 mug 8
Name: amount, dtype: int64
A list of keys makes a pile per customer-and-item pair. A blank means the same as the row above. Two keys give two levels of row labels, which is awkward to work with, so turn the result back into a table:
totals = orders.groupby("customer_id")["amount"].sum()
print(type(totals).__name__)
table = totals.reset_index()
print(table)
print(type(table).__name__)
other = orders.groupby("customer_id", as_index=False)
print(other["amount"].sum())
Series
customer_id amount
0 1 60
1 2 48
2 3 12
3 9 8
DataFrame
customer_id amount
0 1 60
1 2 48
2 3 12
3 9 8
reset_index() moves the labels back into a column with fresh row numbers. as_index=False gives the identical table. You'll see both in other people's code.
merge: two tables and a zip
The orders table doesn't know any names or cities; those are in customers. Picture a zip: customers on one side, orders on the other, and the teeth are customer_id. Where the ids match, the teeth lock and two rows become one longer row. Maya has three orders, so her row locks three times. Ravi, Sofia and customer 9 have nothing to lock with. What happens to those leftovers is the main choice in a merge.
from shop import customers, orders
both = customers.merge(
orders, on="customer_id", how="inner"
)
print(both)
print(len(customers), len(orders), len(both))
customer_id name city order_id item amount
0 1 Maya Lisbon 101 notebook 12
1 1 Maya Lisbon 103 mug 8
2 1 Maya Lisbon 106 lamp 40
3 2 Omar Oslo 102 lamp 40
4 2 Omar Oslo 105 mug 8
5 3 Lena Lisbon 104 notebook 12
5 7 6
on names the column both tables share. how="inner" keeps only rows that found a partner, and it's the default. Five customers and seven orders give six rows.
how="left" and how="outer"
left = customers.merge(
orders, on="customer_id", how="left"
)
print(left)
customer_id name city order_id item amount
0 1 Maya Lisbon 101.0 notebook 12.0
1 1 Maya Lisbon 103.0 mug 8.0
2 1 Maya Lisbon 106.0 lamp 40.0
3 2 Omar Oslo 102.0 lamp 40.0
4 2 Omar Oslo 105.0 mug 8.0
5 3 Lena Lisbon 104.0 notebook 12.0
6 4 Ravi Lima NaN NaN NaN
7 5 Sofia Oslo NaN NaN NaN
Left keeps every row of the table before the dot. Ravi and Sofia stay, with NaN in the order cells, and order_id becomes 101.0 because NaN is a float. Use left for "which customers have never ordered?".
everything = customers.merge(
orders, on="customer_id", how="outer"
)
print(everything)
print(len(everything))
customer_id name city order_id item amount
0 1 Maya Lisbon 101.0 notebook 12.0
1 1 Maya Lisbon 103.0 mug 8.0
2 1 Maya Lisbon 106.0 lamp 40.0
3 2 Omar Oslo 102.0 lamp 40.0
4 2 Omar Oslo 105.0 mug 8.0
5 3 Lena Lisbon 104.0 notebook 12.0
6 4 Ravi Lima NaN NaN NaN
7 5 Sofia Oslo NaN NaN NaN
8 9 NaN NaN 107.0 mug 8.0
9
Outer keeps everything, including customer 9's order with no name or city. It's handy for spotting data that doesn't line up.
When the key names differ
people = customers.rename(columns={"customer_id": "id"})
joined = people.merge(
orders, left_on="id", right_on="customer_id"
)
print(joined.columns.tolist())
['id', 'name', 'city', 'order_id', 'customer_id', 'item', 'amount']
With no shared name, use left_on and right_on. Both key columns are kept, so you have the same value twice and can drop one.
The duplicate key trap
Now say the customers table has customer 1 twice: Maya in Lisbon and Maya in Porto. Maybe she moved and someone added a new row.
import pandas as pd
from shop import orders
customers = pd.DataFrame(
[
(1, "Maya", "Lisbon"),
(1, "Maya", "Porto"),
(2, "Omar", "Oslo"),
],
columns=["customer_id", "name", "city"],
)
joined = customers.merge(orders, on="customer_id")
print(joined[["name", "city", "order_id", "amount"]])
print(len(joined))
print(orders["amount"].sum())
print(joined["amount"].sum())
name city order_id amount
0 Maya Lisbon 101 12
1 Maya Lisbon 103 8
2 Maya Lisbon 106 40
3 Maya Porto 101 12
4 Maya Porto 103 8
5 Maya Porto 106 40
6 Omar Oslo 102 40
7 Omar Oslo 105 8
8
128
168
Both Maya rows match all three of her orders: two times three gives six rows. No error, no warning, and the table looks fine. But all the orders add up to 128 and the joined table says 168, even though some orders didn't match at all. Maya's 60 got counted twice. So check your key before you merge:
print(customers["customer_id"].is_unique)
try:
customers.merge(
orders, on="customer_id", validate="one_to_many"
)
except pd.errors.MergeError as err:
print(str(err).splitlines()[0])
False
Merge keys are not unique in left dataset; not a one-to-many merge
validate="one_to_many" says "each customer once on the left, any number of orders on the right". When the data breaks that promise, pandas raises a MergeError instead of doubling rows. One small argument turns a silent problem into a clear one.
concat stacks tables
import pandas as pd
from shop import orders
more = pd.DataFrame(
[(108, 4, "lamp", 40), (109, 5, "mug", 8)],
columns=orders.columns,
)
stacked = pd.concat([orders, more])
print(stacked.index.tolist())
fresh = pd.concat([orders, more], ignore_index=True)
print(fresh.index.tolist())
print(len(orders), len(more), len(fresh))
[0, 1, 2, 3, 4, 5, 6, 0, 1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
7 2 9
Merge matches rows; concat just puts one sheet under another. Each table keeps its own labels unless you pass ignore_index=True. With axis=1, concat goes sideways and lines rows up by index, not by any key: three ratings next to five customer names leave Ravi and Sofia with NaN. So if rows belong together because of a key, use merge. If you're only stacking or placing side by side, use concat.
Recap
| Task | Code |
|---|---|
| Total per group | df.groupby("key")["col"].sum() |
| Several summaries, named | .agg(spent=("amount", "sum"), ...) |
| Back to a table | .reset_index() or groupby(..., as_index=False) |
| Join on a key | a.merge(b, on="key", how="inner" / "left" / "outer") |
| Different key names | left_on=..., right_on=... |
| Guard the key | is_unique, validate="one_to_many" |
| Stack | pd.concat([a, b], ignore_index=True) |
Try it yourself: work out the total spend per city by merging customers and orders and then grouping by city. Lisbon should come to 72. Or ask an AI tool to write it, then read every line it gives you. The same ideas in SQL (GROUP BY and JOIN) are in SQL essentials.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
