(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisbon

How to normalize heterogeneous schemas in ETL: step by step

João Barros 23 de November de 2026 5 min read

Working with multiple sources that represent the same domain in different ways is common: columns with different names, different types and partial structures. This tutorial shows how to normalize heterogeneous schemas in ETL to obtain a coherent table, useful for reporting and Machine Learning.

Prerequisites

  • Python 3.8+ installed
  • Libraries: pandas and pyarrow (install with pip)
  • Text editor or IDE and access to example CSV files
  • Basic knowledge of ETL and tabular manipulation

Step 1: Understand the problem and map the target model

Before transforming, define the target model (canonical schema). Identify mandatory fields, types and synonyms. Example: we want a "customers" table with: customer_id (string), name (string), email (string), country (string), signup_date (datetime), active (boolean).

Step 2: Collect and inspect the sources

Load the different sources to understand variations: column names, date formats, boolean flags or country codes. Take samples to identify edge cases.

import pandas as pd
# Exemplos de ficheiros de origem
src1 = pd.read_csv('customers_a.csv')  # coluna 'id', 'full_name', 'email', 'country_code', 'joined'
src2 = pd.read_csv('customers_b.csv')  # coluna 'customer_id', 'name', 'email_address', 'country', 'signup'
src3 = pd.read_csv('customers_c.csv')  # coluna 'uid', 'first_name','last_name','email','active_flag'

print(src1.head())
print(src2.head())
print(src3.head())

Step 3: Define mappings and transformation rules

Create a map that translates column names and rules per source: concatenate names, convert dates, normalize flags and country codes. Keep rules explicit to ease maintenance.

# Mapeamentos por ficheiro
mappings = {
    'src1': {
        'customer_id': 'id',
        'name': 'full_name',
        'email': 'email',
        'country': 'country_code',
        'signup_date': 'joined',
        'active': None  # não existe nesta fonte
    },
    'src2': {
        'customer_id': 'customer_id',
        'name': 'name',
        'email': 'email_address',
        'country': 'country',
        'signup_date': 'signup',
        'active': None
    },
    'src3': {
        'customer_id': 'uid',
        'name': lambda df: df['first_name'].fillna('') + ' ' + df['last_name'].fillna(''),
        'email': 'email',
        'country': None,
        'signup_date': None,
        'active': 'active_flag'
    }
}

Step 4: Implement normalization functions

Create reusable functions: rename columns, convert types, clean emails, impute values and standardize countries. Test each function with a small sample.

from datetime import datetime

def apply_mapping(df, mapping):
    out = pd.DataFrame()
    for target_col, src in mapping.items():
        if src is None:
            out[target_col] = None
        elif callable(src):
            out[target_col] = src(df)
        else:
            out[target_col] = df.get(src)
    return out

def normalize_email(s):
    return s.str.strip().str.lower().replace('', pd.NA)

def parse_date(s):
    return pd.to_datetime(s, errors='coerce')

# Exemplo de uso numa fonte
n1 = apply_mapping(src1, mappings['src1'])
n1['email'] = normalize_email(n1['email'])
n1['signup_date'] = parse_date(n1['signup_date'])

n2 = apply_mapping(src2, mappings['src2'])
n2['email'] = normalize_email(n2['email'])
n2['signup_date'] = parse_date(n2['signup_date'])

n3 = apply_mapping(src3, mappings['src3'])
n3['email'] = normalize_email(n3['email'])
# active: converter 0/1 ou 'Y'/'N' para boolean
n3['active'] = n3['active'].map({1: True, 0: False, 'Y': True, 'N': False}).fillna(False)

Step 5: Standardize and concatenate

After normalizing columns, set default values for missing columns, ensure types and concatenate. Resolve duplicate conflicts (e.g. same customer_id) with a clear rule: prefer the most recent date.

# Garantir colunas todas presentes
target_cols = ['customer_id','name','email','country','signup_date','active']

all_dfs = [n1, n2, n3]
for df in all_dfs:
    for c in target_cols:
        if c not in df.columns:
            df[c] = pd.NA

# Forçar tipos simples
for df in all_dfs:
    df['customer_id'] = df['customer_id'].astype(str)
    df['name'] = df['name'].astype(str)
    df['email'] = df['email'].astype('string')
    df['signup_date'] = pd.to_datetime(df['signup_date'], errors='coerce')
    df['active'] = df['active'].astype('boolean')

# Concatenar
merged = pd.concat(all_dfs, ignore_index=True)[target_cols]

# Remover duplicados: manter registo com signup_date mais recente
merged = merged.sort_values('signup_date').drop_duplicates(subset=['customer_id'], keep='last')

Step 6: Validate and enrich

Perform simple validations: valid emails, mandatory fields not null, and type consistency. Enrichment can include normalizing country to 2-letter ISO or inferring active from last activity.

# Validação simples de email
valid_email = merged['email'].str.contains(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", na=False)
merged['email_valid'] = valid_email

# Filtrar registos sem customer_id ou nome
clean = merged.dropna(subset=['customer_id','name'])

# Exemplo de normalização de country: mapear nomes comuns
country_map = {'United Kingdom': 'GB', 'Portugal': 'PT', 'UK': 'GB'}
clean['country'] = clean['country'].replace(country_map).fillna('UNKNOWN')

Verify the result

Confirm that the output has the expected schema, correct types and no duplicates by customer_id. Perform checks: record count, percentage of valid emails and manual samples.

print('Registos finais:', len(clean))
print('Emails válidos:', clean['email_valid'].mean())
print(clean.head(10))

# Guardar resultado final
clean.to_parquet('customers_normalized.parquet', index=False)

Conclusion

Normalizing heterogeneous schemas in ETL reduces friction downstream and improves data quality. Next steps: automate with a pipeline (Airflow/Prefect), add unit tests for mappings and create transformation audits. Tip: start with small examples and document each mapping rule — what the rule was and why?