Sub topic 1
Keys and how tables relate
Every merge starts with the same question: which column or columns tell pandas that a row in one table belongs with a row in another? Those columns are the join keys. If you misjudge how the keys relate, the merge can silently drop rows, duplicate rows, or produce a table far larger than either input. This chapter covers how to reason about keys before you write any merge code.
Prerequisites
This chapter assumes you can:
- Write basic Python and run it in a script or notebook.
- Create a DataFrame and select columns with
df["col"]anddf[["a", "b"]]. - Explain what the DataFrame index is and how it differs from a regular column.
- Recognize common pandas dtypes such as
int64,float64,object,string, anddatetime64.
No merge or join experience is needed. The calls to merge that appear here are previews, and later chapters cover them in detail.
What a key is
A key is a column, or a group of columns, whose values identify a row or point to a row in another table. Two kinds matter when you combine tables:
- A primary key identifies each row of its own table. Every value is unique and none is missing. In a
customerstable,customer_idis the primary key. - A foreign key is a column in one table that refers to the primary key of another. In an
orderstable,customer_idis a foreign key that points back tocustomers.
pandas does not enforce either kind. A DataFrame has no declared primary key, and nothing stops a "foreign key" from holding a value that exists nowhere else. The roles exist in your head and in your data, so you have to check them yourself. A merge uses whatever columns you name, whether or not they behave like keys.
Here are the two tables used throughout this chapter.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
"amount": [25.0, 40.0, 15.5, 60.0],
})customers has one row per customer. orders has one row per order. Customer 1 placed two orders, Ben (customer 2) placed none, and order 13 refers to customer 4, who is not in customers.
Relationship types
The relationship between two tables depends on whether the key is unique on each side. There are three cases.
| Relationship | Key unique in left table | Key unique in right table | Example |
|---|---|---|---|
| One-to-one | Yes | Yes | `customers` and a `loyalty_cards` table with one card per customer |
| One-to-many | Yes | No | One customer, many orders |
| Many-to-many | No | No | Students and courses, linked through enrollments |
The relationship type tells you how many rows a merge can produce. A one-to-one merge never produces more rows than the larger input. A one-to-many merge produces one output row for each matching row on the "many" side. A many-to-many merge produces every pairing of the matching rows, so it can grow quickly. Row-count rules are covered in detail in a later chapter. Here the goal is to find out which relationship you have before you merge.
Many-to-many relationships are rare as a direct join between two tables. They usually come from a third table, such as enrollments, that holds one row per student and course pair. Each original table then has a one-to-many relationship with that bridge table. If you merge two tables on a key that is duplicated on both sides, and you did not expect that, you almost certainly have a data problem.
Checking whether a key is unique
Do not assume a key is unique because its name ends in _id. Test it.
print(customers["customer_id"].is_unique)
print(orders["customer_id"].is_unique)
print(orders["order_id"].is_unique)This prints True, False, True. Series.is_unique returns True when no value repeats. So customer_id is a primary key in customers, order_id is a primary key in orders, and customer_id in orders is a foreign key whose values repeat.
For a fuller profile, including missing values and multi-column keys, a small helper is useful.
def describe_key(df, cols):
cols = [cols] if isinstance(cols, str) else list(cols)
return {
"rows": len(df),
"distinct_keys": len(df.drop_duplicates(subset=cols)),
"missing": int(df[cols].isna().any(axis=1).sum()),
"is_unique": not df.duplicated(subset=cols).any(),
}
print(describe_key(customers, "customer_id"))
print(describe_key(orders, "customer_id"))The output is:
{'rows': 3, 'distinct_keys': 3, 'missing': 0, 'is_unique': True}
{'rows': 4, 'distinct_keys': 3, 'missing': 0, 'is_unique': False}When rows and distinct_keys differ, the key repeats. When missing is above zero, some rows have no usable key.
To see which rows repeat, use duplicated with keep=False, which marks every row in a repeated group instead of only the later ones.
print(orders[orders.duplicated(subset="customer_id", keep=False)])This prints the two orders for customer 1.
Composite keys
Sometimes no single column identifies a row. A table of daily sales per store might repeat store_id on every day and repeat date for every store. Only the pair (store_id, date) is unique. That pair is a composite key.
sales = pd.DataFrame({
"store_id": [1, 1, 2, 2],
"date": ["2026-01-01", "2026-01-02", "2026-01-01", "2026-01-02"],
"units": [5, 7, 3, 4],
})
print(sales["store_id"].is_unique)
print(describe_key(sales, ["store_id", "date"])["is_unique"])The first line prints False and the second prints True. If you join two tables on only part of a composite key, each row matches too many rows on the other side. The merge still runs and still returns a result, but the row count is wrong. When a table needs several columns to identify a row, list all of them when you merge. That is covered in the chapter on choosing keys.
Natural and surrogate keys
A natural key is a value that already means something in the real world, such as an email address, a product SKU, or a country code. A surrogate key is an arbitrary identifier, such as customer_id, created only to identify rows.
- Natural keys are convenient because both tables may already contain them. They are risky because real-world text is messy.
"[email protected]"and"[email protected] "are different strings to pandas. - Surrogate keys are stable and compact, usually integers. They only help if both tables use the same system of identifiers.
When two datasets come from different systems, you often have only natural keys and must clean them before they match. That cleaning is covered in the chapter on key pitfalls.
Finding keys that have no partner
A key value present on one side but absent on the other is an unmatched key. Which rows survive a merge depends on the join type, so find unmatched keys before you choose one. The isin method gives a quick answer.
orphans = orders[~orders["customer_id"].isin(customers["customer_id"])]
no_orders = customers[~customers["customer_id"].isin(orders["customer_id"])]
print(orphans)
print(no_orders)orphans contains order 13, whose customer 4 has no record in customers. no_orders contains Ben. These two small tables are the reason join types exist. An inner merge drops both unmatched rows. A left merge keeps Ben. An outer merge keeps both. The next chapters show how each join type behaves.
In production data, an orphan foreign key often means a real problem, such as a customer deleted from one system but not the other, or an extract taken at a different time. Decide whether the orphan rows should be dropped, kept, or reported before you merge.
Previewing a merge
With the relationship understood, the first merge is a single call.
result = customers.merge(orders, on="customer_id")
print(result)The output has three rows. Ana appears twice, once for each of her orders. Chen appears once. Ben and order 13 are absent because they have no partner. This is a one-to-many merge, and the result has one row per matching row on the many side. You could have predicted that from the checks above:
customer_idis unique incustomers, so each order matches at most one customer.customer_idrepeats inorders, so one customer can match several orders.- Customer 4 has no match, so order 13 is dropped by the default inner join.
Prediction before execution is the habit this chapter is meant to build. If you can state the expected row count before running the merge, you can notice when the actual count differs.
Common mistakes with keys
- Assuming uniqueness. A key that "should" be unique often has duplicates from a bad export or a repeated load. Always run
is_uniqueorduplicatedfirst. - Using a partial composite key. Merging on
store_idalone when the key is(store_id, date)multiplies rows. - Comparing keys of different types. The integer
1and the string"1"do not match. Checkdtypeson both sides. - Ignoring missing values. Rows with
NaNin a key have no meaningful identity. pandas can matchNaNwithNaNin a merge, which pairs unrelated rows. Count the missing keys first. - Treating the index as a key without noticing. A merge with
on=ignores the index, and a join withleft_index=Trueignores columns. Know which one holds your key.
Exercises
Exercise
You have a products table with columns product_id and name, and a reviews table with columns review_id, product_id, and rating. You run products["product_id"].is_unique and reviews["product_id"].is_unique. The first returns True and the second returns False. What relationship do the tables have, and which table's rows determine the row count of an inner merge on product_id?
Show answer
The relationship is one-to-many: each product can have many reviews. In an inner merge, the row count equals the number of reviews whose product_id exists in products, so the reviews table (the "many" side) determines it.
Exercise
Write code that lists the rows of orders whose customer_id does not appear in customers. What does it return for the example tables in this chapter?
Show answer
Use orders[~orders["customer_id"].isin(customers["customer_id"])]. It returns one row: order 13, with customer_id 4 and amount 60.0.
Exercise
A sales table has one row per store per day. Why is sales["store_id"].is_unique False even though the data has no duplicate rows, and which columns should you check for uniqueness instead?
Show answer
Each store appears once for every day, so store_id repeats. The rows are only unique as a pair, so check the composite key ["store_id", "date"] with sales.duplicated(subset=["store_id", "date"]).any().