Preparing tables
Last updated
Real tables have gaps, words where numbers should be, columns measured in grams next to columns measured in millimetres, and a few values a thousand times bigger than the rest. Models need a clean matrix of numbers. This lesson fixes each problem with the right tool, and then puts all the fixes inside one pipeline, so they learn only from the training rows.
By the end of this lesson you can
- Handle missing values by dropping, imputing or flagging them
- Choose a scaler, and say which models need one
- Encode categories with one-hot or ordinal encoding, and tame skewed numbers with a log
- Build a ColumnTransformer that prepares every column inside a pipeline
Missing values
The full penguins table, before Stage 2 quietly dropped the incomplete rows:
Two penguins have no measurements at all, and eleven have no recorded sex. There are three things you can do with a gap:
- Drop the row. Fine when very few rows have gaps and they're missing at random. Here, two of 344 penguins: no loss. But dropping all 11 rows with any gap throws away nine penguins' good measurements because of one blank column.
- Impute: fill the gap with a stand-in, such as the column's median (for numbers) or its commonest value (for categories). The model can then use the rest of the row.
- Flag it: add a column saying "this was missing". Sometimes the gap itself is information. A blank income on a loan form isn't random.
SimpleImputer does the second, and with add_indicator=True the third as well:
The fourth penguin, which had no measurements, now has the median of each column, followed by four 1s saying "these four were filled in". The median is safer than the mean for skewed columns (step 5), because one huge value can drag a mean a long way. Gradient-boosted trees (lesson 4.6) can handle gaps themselves, with no imputing; most other models can't.
Wrong way: filling gaps with the whole table's mean
The quick way is penguins.fillna(penguins.mean(numeric_only=True)), before splitting. But the mean it fills with was worked out from every row, test rows included:
The whole table's mean mass is 4,201.8 g; the training rows' mean is 4,256.8 g. Fill with the first and the training data now holds a number computed partly from the test set. It's lesson 2.10's leakage through scaling, in another form. Here the effect is small, but with more gaps, or a fancier imputer that predicts each gap from the other columns, the test score creeps up for no real reason.
The fix is the same as in lesson 2.10: put the imputer in a pipeline, so it learns its medians from the training rows in each fold, and only applies them to the rest.
Scaling, and which models need it
Lesson 2.4 showed -NN going from 78% to 96% once the features were on one scale. Three common scalers, each tried on a column with outliers, the average number of people per household in 2,000 California districts:
StandardScaler: subtract the mean, divide by the standard deviation (lesson 3.7). The usual choice. Outliers pull the mean and inflate the standard deviation, and the biggest value still lands at 12.MinMaxScaler: squeeze each column into 0 to 1. One extreme value becomes the 1, and everything else is crushed together: here the middle half of the districts sit between 0.14 and 0.21.RobustScaler: subtract the median, divide by the spread of the middle half (the interquartile range). Outliers don't move either, so the bulk of the data keeps a sensible spread.
Which models need scaling at all?
| Needs it | Doesn't |
|---|---|
| Anything built on distances: -NN, -means, SVMs with an RBF kernel, PCA | Trees and the forests and boosting built from them: a split "length ≤ 42" works the same in mm or m |
| Anything trained by gradient descent or with a penalty: linear and logistic regression with ridge or lasso, neural networks | Naive Bayes |
When in doubt, scale: it never hurts a tree, and it often saves the others.
Categories
Lesson 2.3 turned the island into three columns of 0s and 1s, one-hot encoding, because numbering them 1, 2, 3 would tell the model that Torgersen is "more" than Biscoe. Two more details matter in practice:
- A category the encoder never saw in training, here an island called Anvers, would normally be an error.
handle_unknown="ignore"turns it into all 0s instead, so one new value doesn't stop the model working. - A category with hundreds of values, such as a barangay or a product code, makes hundreds of columns.
OneHotEncoder(min_frequency=20)lumps the rare ones together into one "infrequent" column.
When the categories do have an order, such as sizes S, M, L or "never, sometimes, often", one column of 0, 1, 2 keeps that order, and is the right encoding:
Give OrdinalEncoder the order yourself. Left alone, it numbers categories alphabetically: L, M, S.
Skewed numbers and outliers
Many real numbers are skewed: most values are small and a few are huge. Populations, incomes, prices, counts. Here's the population of each district, and its logarithm:
On the left, almost every district is crammed into the first few bars, with a long tail to the right. On the right, after np.log1p (the log of 1 + x, which is fine at 0), the same data spreads into a hump. A linear model, which adds weight × feature, fits much better when a feature's effect is "each doubling adds so much" rather than "each extra person adds so much", and the log turns the first into the second. A skewed label can be logged too: predict log price, then undo it with np.expm1.
Outliers need a decision, not a reflex. A penguin of 42,000 g is a typing mistake: fix or drop it (lesson 4.12 finds such rows). A district with ten times the usual population is real, and the model should see it, logged or robustly scaled. Never drop rows from the test set because they're hard: the real world will send you those too.
Every column at once: ColumnTransformer
Each kind of column needs its own steps. ColumnTransformer sends each list of columns down its own pipeline and joins the results side by side. Follow a column through it:
bill_length_mm, for the first penguin 39.1: SimpleImputer(median), then StandardScaler, and it comes out as −0.88. Every step learns its numbers (medians, means, categories) from the training rows only.
The whole thing, ending in a model, then cross-validated:
All 344 penguins, gaps and all, go in; 99.4% come out right, and nothing leaked, because every imputer, scaler and encoder is refitted on the training folds each time. The second cell lists the nine columns the model sees: four scaled numbers, then three island and two sex columns.
This is the shape of nearly every model on a table from now on: a ColumnTransformer to prepare, then the model, in one pipeline. Lesson 4.2 adds features to it.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- scikit-learn: Imputation of missing values: SimpleImputer, and missing-value indicators
- scikit-learn: Preprocessing data: the scalers and encoders, and when to use each
- scikit-learn: ColumnTransformer for heterogeneous data: routing columns to their own steps
- Kuhn and Johnson, Feature Engineering and Selection, Chapman and Hall/CRC, 2019: chapters 6 and 8: transforming predictors, and handling missing data