Sub topic 7
Encoding categorical features
This chapter assumes you know basic pandas, the scikit-learn fit and transform workflow, and the difference between training and test data. It covers how to turn category columns into numbers a model can use, and which encoder fits which situation.
Why encoding is needed
Most scikit-learn models accept only numbers. A column such as city holds strings, so you must convert it. The right conversion depends on whether the categories have a natural order and how many distinct values there are (the cardinality).
One-hot encoding
One-hot encoding creates one 0/1 column per category. A row has a 1 in the column for its own category and 0 elsewhere. It makes no assumption about order, so it suits nominal columns such as city or color.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"city": ["Paris", "Oslo", "Paris", "Rome"]})
new = pd.DataFrame({"city": ["Oslo", "Madrid"]})
enc = OneHotEncoder(handle_unknown="ignore")
enc.fit(train)
print(enc.get_feature_names_out())
print(enc.transform(new).toarray())The encoder learns the category list from the training data only. "Madrid" was never seen, so with handle_unknown="ignore" it becomes a row of all zeros instead of raising an error. Without that setting, an unseen category at prediction time crashes the pipeline.
Ordinal encoding
Ordinal encoding maps each category to an integer. Use it when the categories have a real order, such as low < medium < high. Pass the order explicitly, because the default is alphabetical.
from sklearn.preprocessing import OrdinalEncoder
sizes = pd.DataFrame({"size": ["small", "large", "medium", "small"]})
ord_enc = OrdinalEncoder(categories=[["small", "medium", "large"]])
print(ord_enc.fit_transform(sizes))Do not apply ordinal encoding to nominal columns in linear models. It tells the model that Rome is "greater than" Oslo, which is meaningless. Tree-based models are less affected, because they can split the integers into groups.
Choosing an encoder
| Situation | Encoder | Main trade-off |
|---|---|---|
| Nominal, few categories | One-hot | Adds one column per category |
| Ordered categories | Ordinal with explicit order | Imposes equal spacing between levels |
| Nominal, many categories | Target encoding (next chapters) | Needs care to avoid leakage |
| Tree model, many categories | Ordinal, or rare-category grouping | Arbitrary order, but compact |
Common errors
- Fitting on all the data. The encoder's category list is learned state. Fit it on training data only, ideally inside a
Pipeline, so test categories do not leak into the vocabulary. - Missing
handle_unknown. New categories appear in production. Sethandle_unknown="ignore"for one-hot, orhandle_unknown="use_encoded_value"withunknown_value=-1for ordinal. - High cardinality with one-hot. A column with 10,000 IDs creates 10,000 columns. Use
min_frequencyto merge rare values into one "infrequent" group. - The dummy variable trap. In an unregularized linear model, one-hot columns sum to 1 and duplicate the intercept. Use
drop="first"there. Regularized models and trees do not need it. - Missing values. Impute first, or treat "missing" as its own category.
enc = OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=2)
enc.fit(train)
print(enc.get_feature_names_out())Here "Oslo" and "Rome" each appear once, so both fall into a shared infrequent column, and only "Paris" keeps its own.
Exercise
A column grade has values "A", "B", "C" with A best. You encode it with OrdinalEncoder() using defaults and the data has the values "C", "A", "B". Why might you still pass categories=[["C", "B", "A"]], and what would the encoded value of "A" be?
Show answer
The default order is alphabetical, which happens to give A=0, B=1, C=2, so the best grade gets the lowest number. Passing categories=[["C", "B", "A"]] makes the numbers rise with quality, so "A" becomes 2. Stating the order explicitly also protects you if the category names change.
Exercise
Your production model fails with an error the first time a customer from a new city appears. Which encoder setting prevents this for one-hot encoding?
Show answer
Set handle_unknown="ignore". An unseen city is then encoded as all zeros instead of raising an error.