Sub topic 7
Encoding categorical features
Most models need numbers, but many columns hold labels such as a city, a plan type or a product code. Encoding turns those labels into numeric columns. This chapter assumes you know the scikit-learn fit/transform workflow, basic pandas, and the data leakage rule: every transformation is fitted on training data only. Pipelines are covered in a later chapter. The examples here use encoders on their own.
Nominal and ordinal columns
The first decision is whether the categories have a meaningful order.
- A nominal column has no order.
citywith values Paris, Lyon and Nice is nominal. - An ordinal column has a natural order.
sizewith values small, medium and large is ordinal.
Treating a nominal column as numbers (Lyon=0, Nice=1, Paris=2) tells a linear model that Paris is "twice" Nice. That relationship is invented. Treating an ordinal column as unordered throws away information that is real.
| Encoding | Output | Best for | Main risk |
|---|---|---|---|
| One-hot | One 0/1 column per category | Nominal, low cardinality | Many columns when cardinality is high |
| Ordinal | One integer column | Truly ordered categories, tree models | Fake order for nominal data in linear models |
| Frequency or count | One numeric column | Medium to high cardinality | Different categories with equal counts collide |
| Hashing | Fixed number of columns | Very high cardinality, streaming | Collisions, columns hard to interpret |
| Target encoding | One numeric column | High cardinality | Leakage unless done carefully |
Target encoding has its own chapter, so this one covers the first four.
One-hot encoding
One-hot encoding creates one column per category. A row has 1 in the column for its category and 0 in all others.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"city": ["Paris", "Lyon", "Paris", "Nice"]})
new = pd.DataFrame({"city": ["Lyon", "Berlin"]})
enc = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
enc.fit(train)
print(enc.get_feature_names_out())
print(enc.transform(new))The categories are learned from train and sorted alphabetically. The printed names are city_Lyon, city_Nice and city_Paris. Lyon becomes [1, 0, 0]. Berlin was never seen in training, so with handle_unknown="ignore" it becomes [0, 0, 0] instead of raising an error.
Why not `pd.get_dummies`
pd.get_dummies is convenient for exploration. In a real workflow it causes trouble. If you call it separately on the training and test sets, the two results can have different columns, because a category may appear in only one of them. It also remembers nothing, so the same logic cannot be applied at serving time. A fitted OneHotEncoder stores its categories and reproduces the same columns every time.
Options worth knowing
handle_unknown="ignore"avoids crashes in production when a new category appears. The default raises an error. That is useful during development because it exposes surprises.drop="first"ordrop="if_binary"removes redundant columns. If you know a row is not Lyon and not Nice, it must be Paris. The redundancy matters for unregularized linear models, where the columns become perfectly collinear (the "dummy variable trap"). Regularized models and trees do not need it. Dropping also makes unknown-category handling less clear, because the all-zero row now means a real category.sparse_output=True(the default) returns a sparse matrix. Keep it when cardinality is high, because most entries are zero.min_frequencyandmax_categoriesgroup rare categories into one "infrequent" column.
Handling rare categories
A column such as zip_code may have thousands of values, many seen once or twice. One-hot encoding them produces thousands of columns that the model can only memorize. Grouping rare values is a cheap fix.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
cities = pd.DataFrame({"city": ["Paris", "Paris", "Paris", "Lyon", "Nice"]})
enc = OneHotEncoder(
handle_unknown="infrequent_if_exist",
min_frequency=2,
sparse_output=False,
)
print(enc.fit_transform(cities))
print(enc.get_feature_names_out())Lyon and Nice each appear once, which is below min_frequency=2, so both are merged into a single city_infrequent_sklearn column next to city_Paris. With handle_unknown="infrequent_if_exist", a city unseen in training is also sent to that infrequent column. Choose the threshold with cross-validation, not by guessing.
Ordinal encoding
OrdinalEncoder maps each category to an integer. For genuinely ordered data, give the order explicitly. Otherwise scikit-learn sorts the labels alphabetically, which would put "large" before "medium" before "small".
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
sizes = pd.DataFrame({"size": ["small", "large", "medium", "small"]})
ord_enc = OrdinalEncoder(
categories=[["small", "medium", "large"]],
handle_unknown="use_encoded_value",
unknown_value=-1,
)
print(ord_enc.fit_transform(sizes).ravel())The output is [0. 2. 1. 0.]. The categories argument is a list with one list of labels per column. Setting unknown_value=-1 makes unseen labels get -1 instead of an error. Remember that -1 then sits below "small", so it looks like an even smaller size. For a linear model, consider whether that is acceptable.
Ordinal codes on nominal columns are a common shortcut with tree-based models. A tree can split the integers many times and isolate any group of categories, so the fake order does little harm. With few categories and deep trees this often works well. With linear models, k-nearest neighbours, or anything distance-based, the fake order is a real error.
High-cardinality columns
When a column has hundreds or thousands of categories, you have several options.
- Group rare values, as shown above, then one-hot encode the rest.
- Frequency encoding: replace each category with how often it appears in the training data. It is one numeric column. It assumes that popularity is informative, and two unrelated categories with the same count become identical.
- Hashing:
FeatureHasherorHashingVectorizermaps categories into a fixed number of columns with a hash function. It needs no stored vocabulary and handles new values naturally. The cost is collisions, where different categories share a column, and columns you cannot map back to a category. - Target encoding, using the label to summarize each category. It is powerful but easy to leak, so it is treated separately.
The decision below summarizes the usual path.
Common errors
- Fitting the encoder on the full dataset before splitting. The categories seen only in the test set then leak into training. Fit on training data and call
transformon the rest. - Forgetting missing values.
OneHotEncodertreatsNaNas its own category in recent versions, andOrdinalEncodercan encode it withencoded_missing_value. Decide on purpose. You can impute with the most frequent value, or keep "missing" as a category, which is often informative. - Letting the default alphabetical order define an ordinal feature.
- Leaving
handle_unknownat its default in a service that will see new categories. - Encoding an ID column. A customer ID with one row per customer is not a feature. One-hot encoding it creates a column per row, and the model memorizes it.
- Comparing coefficient sizes across one-hot columns without checking
drop. With collinear columns, individual coefficients are not interpretable.
Exercise
A column plan has values "free", "basic" and "pro". A new value "enterprise" appears in production data that was never in training. You use OneHotEncoder with handle_unknown="ignore". What does the encoded row look like, and what is one risk of this choice?
Show answer
The row is all zeros across the three plan columns (planbasic, planfree, plan_pro). The model gets no error, but an all-zero row looks the same as having no plan information at all, so the model may treat "enterprise" customers like an average or baseline case. The silent failure is the risk, so unknown-category rates should be monitored. If the category deserves its own treatment, retrain with it included.
Exercise
You have a country column with 180 values, where 120 of them cover fewer than 0.5% of rows each. You are training a logistic regression. Which encoding would you try first, and which setting controls the grouping?
Show answer
Use OneHotEncoder with the rare countries grouped. Set minfrequency (as a fraction such as 0.005, or a count) with handleunknown="infrequentifexist", so rare and unseen countries share one infrequent column. One-hot suits a linear model because it adds no fake order. Pick the threshold by cross-validation.