Reading history

Encoding Categorical Data in Python: One-Hot, Ordinal and Target Encoding

7 min read 1 views

Learn to encode categorical data in Python with scikit-learn: OrdinalEncoder, OneHotEncoder, unseen and rare categories, and TargetEncoder for high-cardinality columns.

Models work with numbers, but many useful columns hold words: a city, a shop, a size. Encoding turns these categories into numbers the model can use. This lesson compares the three main encoders in scikit-learn and shows how to handle categories that are rare, very many, or never seen during training.

In this lesson you will learn

  • When to use OrdinalEncoder and when to use OneHotEncoder
  • How to handle a category the model has never seen
  • How to group rare categories with min_frequency
  • How TargetEncoder deals with columns that have hundreds of values
  • Why target encoding can leak the answer, and how scikit-learn prevents it

You should know data preprocessing and pipelines and ColumnTransformer.

Ordinal and One-Hot Encoding

Ask one question first: do the categories have a natural order? Sizes do (small, medium, large). Cities do not; Dhaka is not “more” than Khulna.

import pandas as pd
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder

train = pd.DataFrame({
    "size": ["small", "large", "medium", "small"],
    "city": ["Dhaka", "Sylhet", "Dhaka", "Khulna"],
})
new = pd.DataFrame({"size": ["medium"], "city": ["Rajshahi"]})   # a city never seen

# Ordinal: the categories have a natural order
ordenc = OrdinalEncoder(categories=[["small", "medium", "large"]])
print("Ordinal sizes:", ordenc.fit_transform(train[["size"]]).ravel())

# One-hot: no order, one 0/1 column per city
ohe = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
ohe.fit(train[["city"]])
print("Columns:", list(ohe.get_feature_names_out()))
print(ohe.transform(train[["city"]]))
print("Unseen city ->", ohe.transform(new[["city"]]))

Output

Ordinal sizes: [0. 2. 1. 0.]
Columns: ['city_Dhaka', 'city_Khulna', 'city_Sylhet']
[[1. 0. 0.]
 [0. 0. 1.]
 [1. 0. 0.]
 [0. 1. 0.]]
Unseen city -> [[0. 0. 0.]]
  • OrdinalEncoder maps each category to one number. Passing categories=[["small", "medium", "large"]] sets the order yourself. Without it, scikit-learn sorts the words alphabetically, which would put “large” before “medium”.
  • OneHotEncoder makes one 0/1 column per city. Each row has a single 1 in the column for its own city.
  • Rajshahi never appeared in training. With handle_unknown="ignore" it becomes a row of all zeros instead of crashing the model at prediction time.

Never feed unordered categories through an ordinal encoder into a linear model. If Dhaka = 0, Khulna = 1 and Sylhet = 2, the model will assume Khulna sits halfway between the other two. Tree models cope better with this, but one-hot is the safe default.

When a Column Has Hundreds of Values

One-hot gets awkward when a column has many distinct values, such as shop IDs, product codes or postcodes. You get hundreds of columns, and rare values have too few rows to learn from. There are two common fixes:

  • Group rare values. min_frequency=10 puts every category with fewer than 10 rows into one shared “infrequent” column.
  • Target encoding. Replace each category with the average target value for that category, such as the return rate of each shop. One column, however many categories there are.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, TargetEncoder

# 4,000 orders from 300 shops; some shops return far more items than others
rng = np.random.default_rng(3)
n, shops = 4000, 300
shop_rate = rng.beta(2, 8, shops)                 # each shop's true return rate
shop = rng.integers(0, shops, n)
df = pd.DataFrame({"shop": "S" + pd.Series(shop).astype(str)})
y = (rng.random(n) < shop_rate[shop]).astype(int)
print("Distinct shops:", df.shop.nunique())

models = {
    "one-hot (min_frequency=10)": make_pipeline(
        OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=10),
        LogisticRegression(max_iter=1000)),
    "target encoder": make_pipeline(
        TargetEncoder(cv=KFold(5, shuffle=True, random_state=0)),
        LogisticRegression()),
}
for name, model in models.items():
    auc = cross_val_score(model, df, y, cv=5, scoring="roc_auc").mean()
    print(f"{name:28} AUC {auc:.3f}")

model = models["one-hot (min_frequency=10)"].fit(df, y)
print("One-hot columns:", len(model[0].get_feature_names_out()))
te = models["target encoder"].fit(df, y)[0]
s0 = y[df.shop == "S0"]
print("S0 orders:", len(s0), "| returned:", s0.sum(), "| raw rate:", round(s0.mean(), 3))
print("Overall return rate:", round(y.mean(), 3))
print("Encoded value for S0:", te.transform(pd.DataFrame({"shop": ["S0"]})).round(3).ravel())

Output

Distinct shops: 300
one-hot (min_frequency=10)   AUC 0.622
target encoder               AUC 0.646
One-hot columns: 249
S0 orders: 14 | returned: 8 | raw rate: 0.571
Overall return rate: 0.206
Encoded value for S0: [0.536]
  • 248 shops have at least 10 orders and get their own column. The other 52 share one infrequent column, giving 249 columns in total.
  • TargetEncoder produces a single column and scores a slightly higher AUC here.
  • Shop S0 has only 14 orders, 8 of them returned. Its raw rate of 0.571 is shaky with so few rows, so the encoder pulls it toward the overall rate of 0.206. The result is 0.536. Categories with many rows keep values close to their own rate; tiny ones move further toward the average. This is called smoothing.

The Leakage Trap in Target Encoding

Target encoding uses the answer column to build a feature. If a row’s own label helps compute its encoded value, the model sees a hint of the answer and its training score looks far better than reality. A shop with a single order is the extreme case: its encoded value would simply be that order’s label.

scikit-learn guards against this with cross fitting. When you call fit_transform (which a pipeline does during fit), the training rows are split into folds and each fold is encoded using only the other folds. Calling transform later on new data uses encodings learned from all training rows. Two rules follow:

  1. Keep TargetEncoder inside a pipeline so cross fitting happens automatically.
  2. Do not call fit(X, y) and then transform(X) on the same training rows. That skips cross fitting and leaks the labels.

Which Encoder Should You Use?

SituationEncoderNotes
Categories with a real orderOrdinalEncoderPass categories= to set the order
Few unordered categoriesOneHotEncoderAdd handle_unknown="ignore"
Many categories, some rareOneHotEncoder(min_frequency=...)Rare values share one column
Hundreds or thousands of categoriesTargetEncoderKeep it inside a pipeline
Tree-based gradient boostingHistGradientBoosting...(categorical_features="from_dtype")Handles pandas category columns natively

Common Mistakes

  1. Encoding before splitting. Fit encoders on the training data only, inside a pipeline.
  2. Forgetting unseen categories. Without handle_unknown, a new city in production raises an error.
  3. Treating ID numbers as numeric features. A customer ID of 5000 is not “bigger” than ID 12. Treat codes like these as categories or drop them.
  4. Using pandas get_dummies separately on train and test. If a category appears in only one of them, the two tables end up with different columns.

Practice Exercises

Exercise 1. Encode the education levels “school”, “college” and “university” so that the numbers follow that order.

Show answer
enc = OrdinalEncoder(categories=[["school", "college", "university"]])
print(enc.fit_transform([["college"], ["school"], ["university"]]).ravel())
# [1. 0. 2.]

Exercise 2. One-hot encode cities, but drop one column to avoid a redundant column in a plain linear regression. Keep unknown cities from crashing.

Show answer
ohe = OneHotEncoder(drop="first", handle_unknown="ignore", sparse_output=False)

With drop="first", the first city becomes the baseline row of all zeros. scikit-learn allows this together with handle_unknown="ignore", but it will warn you at prediction time, because an unknown city then looks the same as the baseline city.

Frequently Asked Questions

Is one-hot encoding the same as dummy variables?

Yes. “Dummy variables” is the statistics name for the same 0/1 columns. Statistics books often drop one column per feature; machine learning code usually keeps all of them and relies on regularization.

Does target encoding work for regression?

Yes. For a numeric target, each category becomes a smoothed average of the target. TargetEncoder detects whether the target is binary, multiclass or continuous.

Do tree models need one-hot encoding?

Not always. Trees can split on ordinal codes, and HistGradientBoostingClassifier can treat a column as categorical directly. One-hot still works well for columns with few values.

Summary

  • Ordered categories: OrdinalEncoder with an explicit order.
  • Unordered categories: OneHotEncoder(handle_unknown="ignore").
  • Many rare values: group them with min_frequency.
  • Very many values: TargetEncoder, which smooths small categories and uses cross fitting.
  • Always encode inside a pipeline.

Next: Multiclass Classification in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *