Join cardinality
Quick answer
A join combines tables using a shared key. Cardinality describes how many rows on either side can match a key: one-to-one, many-to-one, one-to-many or many-to-many. A many-to-one left join is common when attaching one device description to each reading. Validate uniqueness and audit unmatched keys before modeling. Examples run locally on Python 3.13.5 and pandas 2.2.3; ByteMind package support is not verified. All data are synthetic.
Preserve readings with a validated left join
The reading table can contain repeated device IDs; the metadata table must contain one row per device. indicator records whether a match occurred.
import pandas as pdreadings = pd.DataFrame({'device': ['a', 'b', 'a', 'c'], 'temp': [20, 22, 21, 18]})meta = pd.DataFrame({'device': ['a', 'b'], 'site': ['north', 'south']})out = readings.merge(meta, on='device', how='left', validate='many_to_one', indicator=True)print(len(out))print(out['_merge'].astype(str).tolist())print(out.loc[out['_merge'] == 'left_only', 'device'].tolist())Expected output (pandas 2.2.3):
4['both', 'both', 'both', 'left_only']['c']The unknown device is retained, not dropped; its metadata is missing. This is a data-quality issue to investigate before feature creation.
Detect duplicate lookup keys
If a key appears twice on each side, the unrestricted join produces four matches. Reject that when metadata should have unique keys.
import pandas as pdleft = pd.DataFrame({'key': ['a', 'a']})right = pd.DataFrame({'key': ['a', 'a'], 'value': [1, 2]})print(len(left.merge(right, on='key')))try: left.merge(right, on='key', validate='many_to_one')except pd.errors.MergeError: print('duplicate lookup key rejected')Expected output (pandas 2.2.3):
4duplicate lookup key rejectedA mistaken join can multiply rows, overweight some observations and invalidate evaluation. Resolve why duplicates exist; do not arbitrarily keep the first.
Common mistakes
Unlike typical SQL equality joins, pandas merge can match missing keys to missing keys. Reject or quarantine missing identifiers before joining. Explicitly specify on and how. An inner join discards unmatched rows; quantify that loss. Never join future information to earlier prediction rows.
Practice and next steps
Predict how many rows a join produces for three left and two right rows with the same key. Decide how to handle an unknown metadata key. Try the pure-Python reasoning challenge and knowledge check separately; these do not assess pandas API execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Join cardinality — knowledge check
Apply tabular data reasoning to new synthetic fixtures.
Three left rows and two right rows share one key. How many inner matches?
What must be unique in a many-to-one merge?
Which indicator shows an unmatched left row?
What should happen to null identifier keys before joining?
Why is a future metadata snapshot risky?