Preparing Tabular Data
The toolkit sections taught each technique on its own. Real work strings them together, and the order matters. This lesson walks one messy table, a small loan-application dataset, through the six steps of tabular preparation: inspect the columns and types, clean missing and invalid values, encode categories, scale numbers where the model needs it, engineer and select features, and split without leakage. Everything learned from data ends up inside one scikit-learn pipeline.
Step 1 and 2: inspect, then clean with fixed rules
Inspection (covered in depth in Dataset Inspection) tells you what each column really is. Cleaning that follows fixed rules, the same for every row and learned from nothing, can run before the split: parsing numbers stored as text, mapping placeholders to NaN, unifying category spellings, dropping exact duplicates. Anything that learns from the data (a median, a category list, a mean) waits for the pipeline.
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
n = 600
df = pd.DataFrame({
"income": rng.lognormal(10.6, 0.5, n).round(-2),
"debt": rng.gamma(2.0, 6000, n).round(-1),
"age": rng.integers(19, 75, n),
"employment": rng.choice(["salaried", "Salaried ", "self-employed", "unemployed", "retired"], n, p=[0.4, 0.15, 0.2, 0.1, 0.15]),
"education": rng.choice(["secondary", "bachelor", "master", "doctorate"], n, p=[0.35, 0.4, 0.2, 0.05]),
"region": rng.choice([f"R{i:02d}" for i in range(25)], n),
})
risk = 1.8 * df["debt"] / df["income"] + 0.9 * (df["employment"] == "unemployed") - 0.012 * df["age"]
df["default"] = (rng.random(n) < 1 / (1 + np.exp(-(risk - 0.6) * 3))).astype(int)
# mess it up the way real exports do
df["income"] = df["income"].astype(object)
df.loc[rng.choice(n, 40, replace=False), "income"] = "n/a"
df.loc[rng.choice(n, 25, replace=False), "age"] = -1
df.loc[rng.choice(n, 30, replace=False), "employment"] = None
df = pd.concat([df, df.iloc[:12]], ignore_index=True)
print("text (object) columns:", df.select_dtypes("object").columns.tolist())
print("employment spellings:", sorted(df["employment"].dropna().unique().tolist()))
print("rows:", len(df), "| exact duplicates:", int(df.duplicated().sum()))
clean = df.drop_duplicates().copy()
clean["income"] = pd.to_numeric(clean["income"], errors="coerce")
clean["age"] = clean["age"].where(clean["age"].between(16, 110))
clean["employment"] = clean["employment"].str.strip().str.lower()
print("after cleaning:", len(clean), "rows")
print("missing:", clean.isna().sum()[lambda s: s > 0].to_dict())
print("employment after:", sorted(clean["employment"].dropna().unique().tolist()))
print("default rate:", round(clean["default"].mean(), 3))text (object) columns: ['income', 'employment', 'education', 'region']
employment spellings: ['Salaried ', 'retired', 'salaried', 'self-employed', 'unemployed']
rows: 612 | exact duplicates: 12
after cleaning: 600 rows
missing: {'income': 40, 'age': 25, 'employment': 30}
employment after: ['retired', 'salaried', 'self-employed', 'unemployed']
default rate: 0.292
Inspection finds the usual export damage: income is stored as text (object) because of the "n/a" strings, employment has a "Salaried " variant with a capital and a trailing space, and 12 rows are exact duplicates. After the fixed-rule cleaning, 600 rows remain, with 40 missing incomes, 25 missing ages (the -1 placeholders, now NaN) and 30 missing employment values, four clean employment categories, and a default rate of 0.292. Nothing here was learned from the data, so it is safe before the split.
The cleaning steps are logged in the code itself, which is the minimal version of the cleaning log from Corrupted Files and the Cleaning Log.
Steps 3 to 6: one pipeline, fitted on training rows only
Now the learned steps. Numbers get median imputation with a missing indicator, an engineered debt-to-income ratio, a log transform for the skewed money columns and standardisation. employment is nominal, so it gets a constant fill and one-hot encoding; education is ordered, so an OrdinalEncoder with the explicit order; region has 25 levels, so a target encoder that cross-fits inside the pipeline. The split is stratified because the classes are unbalanced, and every score comes from cross-validation on the training part.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, OrdinalEncoder, StandardScaler, TargetEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import roc_auc_score
rng = np.random.default_rng(7)
n = 600
df = pd.DataFrame({
"income": rng.lognormal(10.6, 0.5, n).round(-2),
"debt": rng.gamma(2.0, 6000, n).round(-1),
"age": rng.integers(19, 75, n).astype(float),
"employment": rng.choice(["salaried", "self-employed", "unemployed", "retired"], n, p=[0.55, 0.2, 0.1, 0.15]),
"education": rng.choice(["secondary", "bachelor", "master", "doctorate"], n, p=[0.35, 0.4, 0.2, 0.05]),
"region": rng.choice([f"R{i:02d}" for i in range(25)], n),
})
risk = 1.8 * df["debt"] / df["income"] + 0.9 * (df["employment"] == "unemployed") - 0.012 * df["age"]
y = (rng.random(n) < 1 / (1 + np.exp(-(risk - 0.6) * 3))).astype(int)
df.loc[rng.choice(n, 40, replace=False), "income"] = np.nan
df.loc[rng.choice(n, 25, replace=False), "age"] = np.nan
df.loc[rng.choice(n, 30, replace=False), "employment"] = np.nan
def debt_to_income(X):
return (X["debt"] / X["income"]).to_frame("debt_to_income")
money = make_pipeline(SimpleImputer(strategy="median", add_indicator=True),
FunctionTransformer(np.log1p), StandardScaler())
ratio = make_pipeline(FunctionTransformer(debt_to_income),
SimpleImputer(strategy="median"), StandardScaler())
prep = ColumnTransformer([
("money", money, ["income", "debt"]),
("ratio", ratio, ["income", "debt"]),
("age", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age"]),
("employment", make_pipeline(SimpleImputer(strategy="constant", fill_value="unknown"),
OneHotEncoder(handle_unknown="ignore")), ["employment"]),
("education", OrdinalEncoder(categories=[["secondary", "bachelor", "master", "doctorate"]]), ["education"]),
("region", TargetEncoder(target_type="binary", random_state=0), ["region"]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
X_train, X_test, y_train, y_test = train_test_split(df, y, test_size=0.25, stratify=y, random_state=0)
cv = cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc")
print(f"train rows {len(X_train)}, test rows {len(X_test)}, positives {y_train.mean():.3f} / {y_test.mean():.3f}")
print(f"5-fold CV ROC AUC on training part: {cv.mean():.3f} +- {cv.std():.3f}")
model.fit(X_train, y_train)
print(f"test ROC AUC (used once): {roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]):.3f}")
print("model inputs:", model.named_steps["prep"].transform(X_test).shape[1], "columns")train rows 450, test rows 150, positives 0.291 / 0.293
5-fold CV ROC AUC on training part: 0.852 +- 0.022
test ROC AUC (used once): 0.807
model inputs: 12 columns
The stratified split keeps the positive share almost equal on both sides (0.291 and 0.293). Five-fold cross-validation on the 450 training rows gives a ROC AUC of 0.852 (standard deviation 0.022); the single test evaluation on 150 rows gives 0.807. The difference is within what one small test set can vary, and both numbers are honest because every fitted step lives in the pipeline. The model sees 12 columns: two log-scaled money columns plus an income-missing indicator, the ratio, age, five one-hot employment columns (four categories and unknown), the education code and the region encoding.
The test score is computed once, at the end, after every decision was made on the training part. If you changed the pipeline after looking at it, the test set would turn into a second validation set and stop being an honest estimate.
Feature selection belongs inside too
If you add a selector, it goes into the pipeline after prep, for example ("select", SelectKBest(f_classif, k=8)). Selecting features on the whole table before splitting is the most dramatic leak in the course: the leakage lab gets 0.94 "accuracy" from pure noise that way. See Filter Methods.
A checklist for any table
| Step | Fixed rule, before the split | Learned, inside the pipeline |
|---|---|---|
| Inspect | types, units, keys, grain | |
| Clean | parse types, placeholders to NaN, spellings, duplicates, impossible values to NaN |
|
| Missing values | imputers, indicators | |
| Encode | category lists, ordinal maps, target means | |
| Scale / transform | fixed formulas like log1p (either place) |
means, stds, quantiles |
| Engineer | row-wise formulas (ratios, date parts) | group aggregates, statistics over rows |
| Select | every selector | |
| Split | group / time / stratified, decided by the data's structure (Split Strategies) |
Pitfalls
- Imputing or scaling before the split: the training rows see test statistics.
- Encoding a nominal column with integers: see One-Hot, Ordinal and Label Encoding.
- Duplicates across the split: drop exact duplicates before splitting, and split by entity when one customer has several rows.
- Looking at the test score repeatedly: each look is a small tuning step on the test set.
Practice
- Which of these may run on the whole table before the split: (a) replacing
"n/a"byNaN, (b) filling missing ages with the median age, (c)log1pof income, (d) aregionfrequency table?
Answer
(a) and (c) are fixed, row-by-row rules and are safe anywhere. (b) and (d) learn numbers from the data (a median, counts), so they must be fitted on training rows only, inside the pipeline.
- The applicants table has several rows per customer (one per application). How should you split?
Answer
By customer: GroupShuffleSplit or GroupKFold with groups=customer_id, so no customer appears on both sides. Otherwise the model can recognise a customer it saw in training and the score is too optimistic.
Test yourself
Which step may run before the train/test split?
- Fitting a StandardScaler
- Median imputation
- Converting the text 'n/a' to NaN
- Selecting the 10 features most correlated with the label
Why is the test score in this lesson computed only once?
- It is slow
- Every look that influences a decision turns the test set into a validation set and inflates the estimate
- scikit-learn allows only one call
- Cross-validation already used the test rows
education has the values secondary, bachelor, master, doctorate. Which encoder fits best in the pipeline?
- LabelEncoder
- OrdinalEncoder with the explicit order
- FeatureHasher
- No encoding