TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › One-Hot, Ordinal and Label Encoding

One-Hot, Ordinal and Label Encoding

Most models only accept numbers. A column such as city with values "Hanoi", "Hue" and "Da Nang" has to become numbers before a linear model, a kNN or a neural network can use it. How you turn categories into numbers is not a detail: the wrong encoding invents relationships that are not in the data, and the model happily learns them.

This lesson covers the three encoders you will use most: one-hot, ordinal and label encoding. The Categorical Data lesson of the beginner course shows pd.get_dummies; here we go further, into unknown categories, rare categories, explicit orders and the false-order trap.

Three ideas in one table

Encoder Output for size = S, M, L Says Use for
One-hot three 0/1 columns, exactly one is 1 "these are different things" nominal categories (no order): city, colour, product type
Ordinal one column 0, 1, 2 in an order you give "S < M < L, evenly spaced" ordinal categories with a real order: size, education level, rating
Label one column of integers in alphabetical order (an accident) the target of a classifier, not features

One-hot from scratch

One-hot encoding gives each category its own column. The rule is simple enough to write in NumPy: learn the list of categories on the training data, then mark each row's category.

python · try it yourself
import numpy as np

train = np.array(["red", "green", "blue", "green", "red"])
categories = np.unique(train)              # learned from the training data only
print("categories:", categories.tolist())

def one_hot(values, categories):
    out = np.zeros((len(values), len(categories)), dtype=int)
    for i, v in enumerate(values):
        hits = np.flatnonzero(categories == v)
        if hits.size:                      # an unknown value stays all zeros
            out[i, hits[0]] = 1
    return out

print(one_hot(train, categories))
print("new data:")
print(one_hot(np.array(["blue", "purple"]), categories))
categories: ['blue', 'green', 'red']
[[0 0 1]
 [0 1 0]
 [1 0 0]
 [0 1 0]
 [0 0 1]]
new data:
[[1 0 0]
 [0 0 0]]

Two decisions hide in those few lines. The category list is fitted on the training data, so the encoder produces the same columns for every later batch. And a category never seen in training (purple) becomes a row of zeros instead of a crash or a new column.

One-hot with scikit-learn: unknown and rare categories

OneHotEncoder makes both decisions explicit. handle_unknown="ignore" gives unknown values all zeros. min_frequency groups categories seen fewer times than the threshold into one shared infrequent column, which keeps the number of columns down and stops the model from fitting a coefficient to a category seen twice.

python · try it yourself
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

train = pd.DataFrame({"city": ["Hanoi"] * 5 + ["Hue"] * 4 + ["Da Nang"] * 3 + ["Vinh", "Can Tho"]})
enc = OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=3, sparse_output=False)
enc.fit(train)
print("columns:", enc.get_feature_names_out().tolist())
print("infrequent:", enc.infrequent_categories_[0].tolist())

new = pd.DataFrame({"city": ["Hue", "Vinh", "Da Lat"]})
print(enc.transform(new).astype(int))
columns: ['city_Da Nang', 'city_Hanoi', 'city_Hue', 'city_infrequent_sklearn']
infrequent: ['Can Tho', 'Vinh']
[[0 0 1 0]
 [0 0 0 1]
 [0 0 0 1]]

Vinh and Can Tho appear once each in training, so they share the column city_infrequent_sklearn. With handle_unknown="infrequent_if_exist", the never-seen Da Lat is treated as infrequent too: a sensible default, since a model knows as little about a brand-new city as about a rare one.

One-hot encoding has a cost: a column with 5,000 distinct values becomes 5,000 columns, almost all zeros. scikit-learn returns a sparse matrix by default for that reason. For high-cardinality columns, the next lessons offer frequency, binary and hashing encoders and target encoding.

Note: drop="first" removes one column per feature. It matters for an unregularised linear regression (the dummies plus the intercept are collinear), but most models are regularised or tree-based, and dropping a column makes unknown categories ambiguous. Keep all columns unless you have that specific reason.

Ordinal encoding: you give the order

For a category with a real order, one integer column keeps the information that L is bigger than M. The order must come from you, not from the alphabet:

python · try it yourself
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder

df = pd.DataFrame({"size": ["M", "S", "XL", "L", "M"],
                   "education": ["bachelor", "high school", "master", "phd", "bachelor"]})

alphabetical = OrdinalEncoder().fit(df)
print("alphabetical:", [c.tolist() for c in alphabetical.categories_])

ordered = OrdinalEncoder(
    categories=[["S", "M", "L", "XL"], ["high school", "bachelor", "master", "phd"]],
    handle_unknown="use_encoded_value", unknown_value=-1,
)
codes = ordered.fit_transform(df).astype(int)
print(pd.DataFrame(codes, columns=["size_code", "edu_code"]).join(df))
print(ordered.transform(pd.DataFrame({"size": ["XXL"], "education": ["master"]})).astype(int).tolist())
alphabetical: [['L', 'M', 'S', 'XL'], ['bachelor', 'high school', 'master', 'phd']]
   size_code  edu_code size    education
0          1         1    M     bachelor
1          0         0    S  high school
2          3         2   XL       master
3          2         3    L          phd
4          1         1    M     bachelor
[[-1, 2]]

The default order is alphabetical: L would be 0 and S 2, which is backwards, and bachelor would rank below high school. With an explicit categories list, the codes follow the real order. An unseen size XXL gets -1 (the last line).

Even a correct order encodes an assumption: the step from S to M counts the same as from L to XL. Linear models take that literally. Trees only split on thresholds, so they use the order and ignore the spacing, which is why ordinal codes work well with tree ensembles.

The false-order trap of label encoding

LabelEncoder turns categories into 0, 1, 2, … in alphabetical order. It was designed for the target y of a classifier, where the numbers are only names. Used on a feature, it tells a model that Da Nang (0) < Hanoi (1) < Hue (2), an order that means nothing. The example below makes the damage visible: the label depends on the colour in a way that has no order, and a linear model sees the colours either as one fake-ordered number or as one-hot columns.

python · try it yourself
import numpy as np
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

rng = np.random.default_rng(0)
colours = np.array(["blue", "green", "orange", "red", "white"])
colour = rng.choice(colours, size=600)
# green and white items are returned often, the others rarely: no order in it
p_return = np.where(np.isin(colour, ["green", "white"]), 0.7, 0.2)
y = (rng.random(600) < p_return).astype(int)

X_label = LabelEncoder().fit_transform(colour).reshape(-1, 1)
X_onehot = OneHotEncoder(sparse_output=False).fit_transform(colour.reshape(-1, 1))

print("label codes:", dict(zip(colours.tolist(), LabelEncoder().fit(colour).transform(colours).tolist())))
for name, X in [("label-encoded", X_label), ("one-hot", X_onehot)]:
    acc = cross_val_score(LogisticRegression(), X, y, cv=5).mean()
    print(f"{name:14s} 5-fold accuracy: {acc:.3f}")
label codes: {'blue': 0, 'green': 1, 'orange': 2, 'red': 3, 'white': 4}
label-encoded  5-fold accuracy: 0.677
one-hot        5-fold accuracy: 0.765

With one-hot columns, logistic regression learns one weight per colour and reaches 0.765 accuracy in 5-fold cross-validation. With the label codes blue = 0 … white = 4, it can only draw a single threshold on that made-up axis, so it cannot say "green and white, but not orange or red between them" and drops to 0.677. The colours' alphabetical order is an accident, and the model is forced to treat it as a fact. A tree could recover by splitting several times, but it wastes splits and data doing so.

LabelEncoder also only takes one column (it has no fit on a 2-D table), another hint that it was never meant for features. For features, use OrdinalEncoder with an explicit order, or OneHotEncoder.

Inside a pipeline

Encoders are fitted transformers like scalers, so they belong in a ColumnTransformer inside a Pipeline and are fitted on training data only (the ColumnTransformer lesson shows the mechanics; Pipelines, ColumnTransformer and FunctionTransformer the full pattern). Fitting the category list on all the data is a mild leak: the encoder "knows" categories that only appear in the test set.

Pitfalls

  • Label-encoding features: an invented order. Use LabelEncoder for targets only.
  • Alphabetical ordinal codes: always pass categories= to OrdinalEncoder for ordered data.
  • No plan for unseen categories: production data will contain them. Choose handle_unknown deliberately.
  • One-hot on thousands of levels: a huge sparse matrix and coefficients for categories seen once; group rare levels (min_frequency) or use another encoder.
  • Encoding before splitting: fit the encoder inside the pipeline.

Practice

  1. A column plan has values free, basic, pro, enterprise. Which encoder would you use with logistic regression, and which with a gradient-boosted tree?
Answer

The plans have a natural order of price and features, so an OrdinalEncoder with categories=[["free", "basic", "pro", "enterprise"]] is reasonable for trees. For logistic regression the even spacing is a strong assumption, so one-hot is safer (four columns, the model learns one weight per plan). Comparing both with cross-validation settles it.

  1. Your OneHotEncoder was fitted with the default handle_unknown="error". What happens in production when a new product type appears, and how do you fix it?
Answer

transform raises a ValueError and the prediction request fails. Set handle_unknown="ignore" (all zeros) or "infrequent_if_exist" together with min_frequency (shared infrequent column), and monitor how often unknown values arrive.

Test yourself

What is LabelEncoder designed for?

  1. Nominal features with many levels
  2. The target labels of a classifier
  3. Ordinal features such as size
  4. Text columns

OrdinalEncoder() without arguments encodes sizes S, M, L, XL as which codes?

  1. S=0, M=1, L=2, XL=3
  2. L=0, M=1, S=2, XL=3 (alphabetical)
  3. Random codes
  4. It raises an error

With handle_unknown="ignore", what does OneHotEncoder output for a category it never saw in training?

  1. An error
  2. A new column
  3. A row of zeros for that feature
  4. The most frequent category

What does min_frequency=3 do in OneHotEncoder?

  1. Drops rows with rare categories
  2. Groups categories seen fewer than 3 times in training into one infrequent column
  3. Keeps only 3 columns
  4. Requires 3 rows per category or raises an error