Skip to content

Lesson 3 of 9 · 25m

Loading Data Without Poisoning the Experiment

Turn raw files and database extracts into stable feature matrices while preserving row identity, time order, and missingness semantics.

Most machine-learning projects do not fail at the model. They fail at the boundary where messy operational data becomes a tidy matrix. Rows shift, timestamps parse in the wrong timezone, missing values become zeros, and the target leaks through a column nobody questioned. Data loading is experimental design, not plumbing.

Preserve row identity before transformation

Never assume row order survives joins, deduplication, or distributed reads. Keep a stable identifier until validation is complete:

import pandas as pd

events = pd.read_parquet('events.parquet')
labels = pd.read_csv('labels.csv')

df = events.merge(labels, on='user_id', how='inner', validate='many_to_one')
print(df[['user_id']].is_duplicated().sum())

The validate argument is cheap insurance. A fan-out join can silently duplicate examples and make a weak model look brilliant because the same user appears many times.

Parse time like you mean it

Operational timestamps are rarely clean:

df['created_at'] = pd.to_datetime(df['created_at'], utc=True)
df['created_hour'] = df['created_at'].dt.hour

Convert to UTC first. Daylight-saving transitions, mixed offsets, and naive datetimes create artificial seasonal effects. If the prediction task happens online, only use time features that will exist at inference time. Knowing resolved_at before a ticket is resolved is leakage, not feature engineering.

Missingness is information, but not magic

A missing value can mean "not applicable," "sensor offline," "user refused," or "pipeline bug." Do not flatten those meanings casually:

df['age_missing'] = df['age'].isna().astype(np.int8)
df['age'] = df['age'].fillna(df['age'].median())

The imputation statistic must be learned from training data only, not the full dataset. We will formalize that in pipelines. At the loading stage, preserve raw missingness long enough to diagnose it.

Separate features from labels physically

Use explicit column lists, not blind deletion:

target = 'converted'
features = [
    'account_age_days', 'signup_hour', 'plan_code', 'referral_source',
    'first_week_events', 'country'
]
X = df[features]
y = df[target].astype('int8')

If the target is absent, fail loudly. If a future column appears, do not automatically include it. Schema drift is one of the most common production model failures.

Split before statistics

A train/test split is not merely for evaluation; it protects every learned preprocessing decision:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

For time-dependent systems, random splitting is often wrong. Split by time so training precedes evaluation. A random split can leak future behavior into training through user histories and drifting distributions.

Field notes

  • CSVs do not preserve dtype reliably; prefer parquet for repeated experiments, but still validate schema.
  • pd.read_csv silently mangles mixed types into object columns.
  • Row count after a join is a first-class validation metric.
  • Time zones are features only when they reflect user reality, not pipeline accidents.
  • Save the exact extraction query or snapshot reference with the experiment.

Was this lesson helpful?

Sign in to rate