Sub topic 1
Keys and How Tables Relate
Prerequisites
This chapter assumes you can write basic Python and create a pandas DataFrame from a dictionary. You should also be able to select columns, know what the DataFrame index is, and recognize common dtypes such as int64, float64, and object. You do not need to have used merge before. This chapter prepares the ground for it.
Why keys matter
Data often lives in several tables. A shop might keep customers in one table and orders in another. Combining them means telling pandas which rows belong together. A key is a column, or set of columns, whose values identify that match.
In the example below, customer_id is the key. In customers it identifies one person. In orders it points back to the person who placed the order.
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],
})
print(customers)
print(orders)Two things stand out in this data:
- Ana (1) has two orders, and Ben (2) has none.
- Order 13 belongs to customer 4, who is not in
customers.
A merge has to decide what to do in each of these cases. Later chapters cover those decisions. This chapter covers how to see the relationship before you merge.
Primary and foreign keys
Database terms are useful here, and pandas follows the same ideas.
- A primary key is a column whose values are unique in its table and are never missing.
customer_idincustomersis one. - A foreign key is a column in another table that refers to a primary key.
customer_idinordersis one. Its values can repeat, because one customer can place many orders.
A key can also span several columns. For example, (store_id, date) might identify one row of daily sales. All the columns together must be unique.
Check the key before you merge
pandas does not require keys to be unique. If you assume uniqueness and are wrong, the merged table can quietly gain rows. Check the keys first.
print(customers["customer_id"].is_unique)
print(orders["customer_id"].is_unique)
print(orders["customer_id"].value_counts())
print(orders["customer_id"].isin(customers["customer_id"]))Here is what each line tells you:
is_uniquereturnsTrueforcustomersandFalsefororders.value_counts()shows that customer 1 appears twice.isin()shows which order rows have no matching customer. Order 13 returnsFalse.
For a multi-column key, use df.duplicated(subset=["store_id", "date"]).any(). It returns True if any combination repeats.
Types of relationships
The uniqueness of the key on each side determines the relationship. This is called cardinality.
| Relationship | Left key | Right key | Example |
|---|---|---|---|
| One-to-one | Unique | Unique | Employee and their badge |
| One-to-many | Unique | Repeats | Customer and their orders |
| Many-to-one | Repeats | Unique | Orders and their customer |
| Many-to-many | Repeats | Repeats | Students and courses, without a link table |
Many-to-many is the dangerous case. Each left row pairs with every matching right row, so the result can grow quickly. A later chapter covers row counts in detail.
Keys must be comparable
Pandas matches keys by value equality, so the two key columns need compatible values. These cases cause trouble:
- A key stored as
int64in one table and as text ("1") in the other does not match. - Missing values (
NaN) in a key need special thought. - Text keys that differ in case or spacing, such as
"Ana "and"ana", are different values.
Compare dtypes early:
print(customers["customer_id"].dtype, orders["customer_id"].dtype)A later chapter shows how to fix each of these problems.
Exercises
Exercise
A products table has a sku column with unique values. An inventory table has several rows per sku, one for each warehouse. What is the relationship from products to inventory, and which pandas expression checks that sku is unique in products?
Show answer
It is one-to-many. Check uniqueness with products["sku"].is_unique, which should return True.
Exercise
You have orders and customers. Write one line that returns the order rows whose customer_id does not appear in customers.
Show answer
orders[~orders["customer_id"].isin(customers["customer_id"])]. For the sample data this returns order 13.