Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Machine Learning Notes
Topic #410

Ordinal Encoding

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 EncodingOrdinal Encoding
Order sourceAlphabetical, arbitraryExplicitly specified by you, matching real-world rank
Appropriate forTarget variables (order doesn't matter for classification)Genuinely ordered categorical features
Risk if misusedImplies false order on nominal dataLow 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 OrdinalEncoder infer category order automatically (alphabetical) instead of explicitly passing the true order via categories= — 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.

Related ML Notes

Want to go beyond the notes?

Join CodingNow's Machine Learning course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →