Sub topic 6
Using scikit-learn's OneHotEncoder
This chapter assumes you know pandas DataFrames, NumPy arrays, and the idea of a feature matrix. It also assumes you know why one-hot encoding exists. You will now use scikit-learn's OneHotEncoder and learn its API.
Why use an encoder object
pandas.get_dummies encodes whatever data it receives. OneHotEncoder is a scikit-learn transformer: it follows the same fit and transform pattern as StandardScaler. It first learns the categories, then uses them to build columns. Because the learned categories are stored on the object, you can apply the same encoding to new data later.
Fit, inspect, transform
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
enc = OneHotEncoder(sparse_output=False)
enc.fit(train)
print(enc.categories_)
print(enc.get_feature_names_out())
print(enc.transform(train))The output shows three things:
categories_is a list with one array per input column. Here it holdsblue,green,red, sorted alphabetically.get_feature_names_out()returnscolor_blue,color_green,color_red. The names are the input column name plus the category.transformreturns one row per input row, with a single 1 in each row. Red becomes[0, 0, 1].
fit_transform(train) does both steps in one call. Use it only on training data.
Input must be two-dimensional
Scikit-learn expects a feature matrix, so the encoder rejects a single pandas Series. Passing train["color"] raises a ValueError that says it expected a 2D array. Use double brackets to keep a DataFrame:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({
"color": ["red", "green", "blue"],
"size": ["S", "M", "S"],
})
enc = OneHotEncoder(sparse_output=False)
encoded = enc.fit_transform(df[["color", "size"]])
print(enc.get_feature_names_out())
print(encoded.shape)With several columns, the encoder handles each one independently. The result has columns for every category of every input column, in input order. Here that gives 3 + 2 = 5 columns.
Sparse output
By default, transform returns a SciPy sparse matrix, which stores only the nonzero entries. One-hot data is mostly zeros, so this saves memory when a column has many categories. The examples here pass sparse_output=False so you get a plain NumPy array you can print. Keep the default for large data. If you need a dense array later, call .toarray() on the result.
Going back with inverse_transform
The encoder can map indicator rows back to the original labels:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
enc = OneHotEncoder(sparse_output=False).fit(train)
print(enc.inverse_transform([[0, 0, 1], [1, 0, 0]]))This prints red and blue. It is useful for checking your work and for reading model outputs.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Expected 2D array, got 1D array` | Passed a Series | Use `df[["col"]]` |
| `TypeError` on `sparse=` | Scikit-learn 1.2 or newer | Use `sparse_output=` |
| Unexpected column order | Categories are sorted | Read `categories_` or the feature names |
| `ValueError: Found unknown categories` | New value at transform time | Covered in the unknown-categories chapter |
Exercise
You fit OneHotEncoder(sparse_output=False) on a DataFrame with columns city (3 distinct values) and plan (2 distinct values). How many columns does transform return, and which attribute tells you the categories the encoder learned for each input column?
Show answer
It returns 5 columns, because the encoder creates one indicator column per category of each input column (3 + 2). The categories_ attribute holds the learned categories, as a list with one array per input column.