Ordinal encoding maps ordered categories to integers that preserve their real-world rank — unlike label encoding's arbitrary alphabetical order, you explicitly define which category is "lowest" and which is "highest."
Python Implementation
from sklearn.preprocessing import OrdinalEncoder
import pandas as pd
df = pd.DataFrame({"education": ["Bachelor's", "High School", "Master's", "PhD", "High School"]})
# Explicitly define the true order — this is what makes it "ordinal," not arbitrary
order = [["High School", "Bachelor's", "Master's", "PhD"]]
encoder = OrdinalEncoder(categories=order)
df["education_encoded"] = encoder.fit_transform(df[["education"]])
print(df)
# High School -> 0.0, Bachelor's -> 1.0, Master's -> 2.0, PhD -> 3.0
Expected output: integers that respect the real ordering of education levels — a linear model can now meaningfully use "higher encoded value = more education" as a genuine signal, which label encoding's alphabetical order wouldn't guarantee.
Ordinal Encoding vs Label Encoding — The Key Difference
| Label Encoding | Ordinal Encoding | |
|---|---|---|
| Order source | Alphabetical, arbitrary | Explicitly specified by you, matching real-world rank |
| Appropriate for | Target variables (order doesn't matter for classification) | Genuinely ordered categorical features |
| Risk if misused | Implies false order on nominal data | Low risk — you controlled the mapping directly |
Practical Use Cases
- Education level, income bracket, satisfaction rating, size (S/M/L/XL)
- Any feature where "higher" genuinely means something the model should be able to use directly
Common Mistakes
- Letting
OrdinalEncoderinfer category order automatically (alphabetical) instead of explicitly passing the true order viacategories=— silently produces the same false-order problem as label encoding. - Using ordinal encoding on a feature with no real order (like city) just because it's simpler than one-hot encoding.
Interview Relevance
Q: "When is ordinal encoding preferable to one-hot encoding?" When the categories have a genuine, meaningful rank — ordinal encoding preserves that ordering information in a single numeric column, while one-hot encoding would discard it across multiple binary columns.
Practice Question
Write the scikit-learn code to ordinally encode a "priority" column with values Low, Medium, High, Critical, in that correct order.