Merge/Join and Data Relationships
Learning objective: use one-to-one, one-to-many, many-to-one joins; detect many-to-many explosions.
Before merging two tables, the most important question is not how to write the code, but what relationship the join is expected to have. Getting the relationship wrong still runs, but the row count and meaning of the result will be completely off.
| Relationship | Meaning | Example |
|---|---|---|
| 1:1 | Both tables have only one row per join key | One company matched to its single latest company-profile record |
| 1:N | One row in one table matches several rows in another | One company's master row matched to its several months of monthly data |
| N:1 | Several rows matched to one row in the other table (the reverse view of 1:N) | Several months of monthly data matched back to the same company's master row |
master = pd.read_csv("DS102_Company_Master.csv")
# site_id alone repeats across companies, so it must be paired with company_id to be a unique site
joined = site_long.merge(master, on="company_id", how="left", validate="m:1")
joined.shape[0] == site_long.shape[0] # a correct 1:N/N:1 merge should not change the row countWarning
Suppose site_long has 48 rows, and master should have exactly one row per company_id. If master accidentally has the same company_id twice (say, the same company got loaded into the master file twice), the merge produces 96 rows instead of 48; every month of data is duplicated, and any later sum comes out to twice the correct answer.
- Before merging, ask: should this be 1:1, 1:N, or N:1?
- Use merge(..., validate="1:1" / "1:m" / "m:1") in code so pandas checks the relationship for you and errors when it does not hold
- Always check the row count after merging and compare it against the expected count; not erroring is not enough
- If the row count is much higher than expected, suspect a non-unique join key before using the result
Both tables have repeated values on the same join key, and they are joined directly on it anyway. What is the main risk of doing this?