Situation: I need to join three sources for a dashboard where keys come as ints, strings with leading zeros, and padded codes; I must normalize, deduplicate, join, assert referential integrity, and handle failures.Approach: Normalize all keys to a common canonical string (fixed width), deduplicate, perform left-joins in a controlled order, and assert referential integrity with clear remediation steps.python
import pandas as pd
# Example inputs
a = pd.DataFrame({'id_int':[1,2,3,3],'metric':[10,20,30,30]})
b = pd.DataFrame({'id_str':['001','002','003'],'attr':['x','y','z']})
c = pd.DataFrame({'code_padded':['0001','0002','0004'],'flag':[True,False,True]})
# Canonicalization function: integer-like -> zero-padded string of width 4
def normalize_key(val):
if pd.isna(val):
return None
s = str(val).strip()
# remove non-digit padding like leading/trailing spaces, possible prefixes
s = ''.join(ch for ch in s if ch.isdigit())
if s == '':
return None
return s.zfill(4)
for df, col in [(a,'id_int'), (b,'id_str'), (c,'code_padded')]:
df['key'] = df[col].apply(normalize_key)
# Deduplicate keeping most recent / first occurrence depending on business rule
a = a.drop_duplicates('key', keep='first')
b = b.drop_duplicates('key', keep='first')
c = c.drop_duplicates('key', keep='first')
# Perform joins: start from the primary dataset used by dashboard (assume 'a')
joined = a.merge(b[['key','attr']], on='key', how='left')\
.merge(c[['key','flag']], on='key', how='left')
# Referential integrity checks
keys_a = set(a['key'].dropna())
keys_b = set(b['key'].dropna())
keys_c = set(c['key'].dropna())
missing_in_b = keys_a - keys_b
missing_in_c = keys_a - keys_c
assert len(missing_in_b) == 0 and len(missing_in_c) == 0, "Referential integrity failed"
# If assert fails, handle below (see plan)
Key points:- Normalize to a canonical string avoids type mismatches (int vs '001').- Deduplicate before join to avoid multiplication of rows.- Use left-join from the dashboard's primary table to preserve its row count.- Assert referential integrity by set comparisons and raise clear errors.Plan when referential integrity fails:- Log counts and sample rows causing mismatch and save to monitoring table.- Quick triage: check normalization rules (e.g., non-digits removed incorrectly), then attempt alternate normalization (strip prefixes).- If missing are valid upstream, request backfill or add a lookup mapping table; if intentional (NULLs), flag in dashboard with "missing source" and show count.- Implement automated alerts (email/Slack) with sample rows and remediation owner.- Add unit tests in ETL asserting expected key coverage to prevent regressions.