Sub topic 6
Using scikit-learn's OneHotEncoder
This chapter covers OneHotEncoder from scikit-learn: how it works, how to call it, and the mistakes people commonly make with it. It assumes you know basic Python and pandas DataFrames, can read a NumPy array, and understand what a training and test split is. It also assumes you know the one-hot idea from the previous chapters: one binary column per category, with a 1 marking which category a row has.
Why use an encoder object instead of get_dummies
The pandas function get_dummies looks at whatever DataFrame you give it and builds columns from the values it sees. That is convenient for exploration. It becomes a problem in a modelling workflow, because the test data or future data may contain different categories than the training data. The two results then have different columns.
OneHotEncoder solves this by separating learning from applying. This follows the usual scikit-learn pattern for transformers:
fitlearns the list of categories from the data you pass in.transformconverts data into indicator columns using that stored list.fit_transformdoes both in one call. Use it only on training data.
Because the category list is stored on the encoder object, the output columns have the same names and order every time you call transform. The encoder can also be saved with the rest of a model and reused later.
A first example
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
enc = OneHotEncoder(sparse_output=False)
encoded = enc.fit_transform(df)
print(enc.categories_)
print(enc.get_feature_names_out())
print(encoded)The attribute categories_ is a list with one array per input column. Here it holds ['blue', 'green', 'red']. Categories are sorted alphabetically for strings, or numerically for numbers. The columns of the result follow that order, so the first column means "blue", the second "green", and the third "red". The row for "red" is [0, 0, 1].
Two things to notice:
- The input is a 2D object: a DataFrame or a 2D array. Passing a single Series such as
df["color"]raises an error, because scikit-learn expects a feature matrix. Usedf[["color"]]with double brackets to keep it two-dimensional. - The output is a NumPy array, not a DataFrame. The column names live in
get_feature_names_out().
Sparse output by default
By default, OneHotEncoder returns a SciPy sparse matrix. In a one-hot matrix, almost every entry is 0. A sparse matrix stores only the positions and values of the non-zero entries, which saves a great deal of memory when a column has hundreds of categories.
Setting sparse_output=False returns an ordinary dense NumPy array. That is easier to print and inspect, so the examples in this chapter use it. For real datasets with many categories, keep the default sparse output. Most scikit-learn estimators accept sparse input directly. If you need to look at a sparse result, call .toarray() on it, but only for small data, since that creates the full dense array.
Handling several columns at once
When you pass several columns, the encoder treats each one separately and joins the results side by side.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({
"color": ["red", "green", "blue", "green"],
"size": ["small", "medium", "large", "medium"],
})
enc = OneHotEncoder(sparse_output=False)
encoded = enc.fit_transform(df)
print(enc.get_feature_names_out())
print(encoded.shape)The feature names look like color_blue, color_green, color_red, size_large, size_medium, size_small. The prefix is the original column name. If the DataFrame was fitted with column names, the encoder records them in feature_names_in_. It then checks column names when you call transform, so a renamed or reordered column raises an error. That check is useful, because it catches silent mismatches.
Fit on training data only
The encoder learns something from the data: the set of categories. So it follows the same rule as any other learned step. Fit it on the training data, then apply it to the test data.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
enc = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
enc.fit(train)
print(enc.get_feature_names_out())
print(enc.transform(test))The encoder learned blue, green and red from the training data. In the test data, "green" becomes [0, 1, 0]. The value "purple" was never seen, so it becomes [0, 0, 0].
The common mistake is calling fit_transform on the test set, or fitting on the whole dataset before splitting. Fitting on test data makes the encoder's columns depend on the test set. In a deployed model, you would not have that data at fitting time. Also, if you fit separate encoders on train and test, the two outputs can have different columns or a different column order, and the model then reads the wrong columns.
Unknown categories
The handle_unknown parameter controls what happens at transform time when a category was not seen in fit.
| Value | Behaviour |
|---|---|
| `"error"` (default) | Raises a `ValueError` |
| `"ignore"` | Outputs all zeros for that column |
| `"infrequent_if_exist"` | Maps the value to the infrequent group if one exists, otherwise all zeros |
The default is strict on purpose. A new category means your training data did not represent reality, and you may want to know. In production, though, a crash on one unexpected value is often worse than a prediction made with that feature "switched off". That is why many pipelines use handle_unknown="ignore".
Be aware of a limit: with "ignore", an unseen category looks the same as a row with no indicator set. The model cannot tell "unknown" from anything else, and it treats the row as if that feature carried no information.
Dropping a column
For each input column, the indicator columns always add up to 1. One column is therefore fully determined by the others. Unregularized linear models can struggle with this perfect redundancy. The drop parameter removes one column per feature.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"size": ["small", "medium", "large", "medium"]})
enc = OneHotEncoder(drop="first", sparse_output=False)
print(enc.fit_transform(df))
print(enc.get_feature_names_out())With drop="first", the alphabetically first category, "large", gets no column. A row of all zeros now means "large". The remaining columns are size_medium and size_small.
Other options include drop="if_binary", which drops one column only for features with exactly two categories, and an explicit list or array that names the category to drop for each feature. Tree-based models do not need dropping. Regularized linear models usually do not need it either, but they will not be harmed by it.
Combining drop with handle_unknown="ignore" has a side effect. An unknown category and the dropped category both produce all zeros, so they look identical. Recent scikit-learn versions allow this combination, but check your version's documentation before relying on it.
Rare categories
A column with thousands of distinct values produces thousands of indicator columns, and most are almost always zero. You can limit this by grouping rare categories.
import numpy as np
from sklearn.preprocessing import OneHotEncoder
X = np.array([["a"], ["a"], ["a"], ["b"], ["b"], ["c"], ["d"]])
enc = OneHotEncoder(
min_frequency=2,
handle_unknown="infrequent_if_exist",
sparse_output=False,
)
print(enc.fit_transform(X))
print(enc.get_feature_names_out())Categories "c" and "d" each appear once, which is below min_frequency=2, so they share one column named x0_infrequent_sort. The names x0 and infrequent_sort appear because the input was a NumPy array without column names. You can also use max_categories to cap the total number of output columns per feature. Both options are covered further in the chapter on rare and high-cardinality features.
Quick reference
| Parameter | What it controls | Common setting |
|---|---|---|
| `categories` | Which categories to use, instead of learning them | `"auto"` (default) |
| `drop` | Which column to remove per feature | `None`, `"first"`, `"if_binary"` |
| `sparse_output` | Sparse matrix or dense array | `True` (default) for large data |
| `handle_unknown` | Behaviour for unseen values | `"ignore"` in production |
| `min_frequency` | Group categories that are rarer than this | An integer or a fraction |
| `max_categories` | Cap on output columns per feature | An integer |
| `dtype` | Type of the output numbers | `float64` (default) |
Common errors
ValueError: Found unknown categories ['purple'] in column 0 during transform. The test data holds a value not seen infit. Sethandle_unknown="ignore"or fix the data.Expected 2D array, got 1D array instead. You passed a Series. Usedf[["column"]].- Columns do not line up between train and test. You probably fitted two encoders. Fit once, then call
transformon both sets. - Missing values. Recent versions treat
NaNas its own category rather than raising an error. This is covered in a later chapter. - Mixed types in one column. A column holding both numbers and strings cannot be sorted into a category order. Convert it to strings first.
Exercise
You fit OneHotEncoder(handle_unknown="ignore", sparse_output=False) on a training column holding "cat", "dog" and "bird". At prediction time the value "fish" arrives. What does transform return for that row, and why might this hide a problem?
Show answer
It returns [0, 0, 0], with no error. The encoder has no column for "fish", so every indicator is zero. The risk is that the model cannot tell an unknown animal from any other row with no indicator set, so it treats the feature as carrying no information. If unseen categories become common, predictions may quietly get worse. Monitoring how often unknown values appear helps you notice this.
Exercise
A colleague writes enc = OneHotEncoder(); enc.fit_transform(X_train); enc.fit_transform(X_test) and feeds both outputs to a model. Name two things that can go wrong, and give the fix.
Show answer
First, the second call refits the encoder on the test data, so the categories and column order come from the test set. The training and test matrices can then have different columns, and the model reads the wrong columns. Second, if the test set lacks a category present in training, the output has fewer columns, or if it has a new category, the column count changes. The fix is to call enc.fit(X_train) once and then enc.transform(X_train) and enc.transform(X_test), or to put the encoder in a Pipeline.