Skip to main content
Albero Academy

Encoding Categoricals

Turn text categories into numbers models can use.

Preprocessing8 min

Models work with numbers, but real data has categorical columns (city, colour, grade). Encoding converts them to numeric form — and choosing the right encoding matters.

One-hot encoding

The safe default for unordered categories: one 0/1 column per category, so no false ordering is implied:

OneHotEncoder
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
X_enc = enc.fit_transform(X[["city"]])
# "Pune"/"Delhi"/"Mumbai" → three 0/1 columns

Ordinal encoding

only for ordered categories
from sklearn.preprocessing import OrdinalEncoder
enc = OrdinalEncoder(categories=[["low", "mid", "high"]])
# maps to 0, 1, 2 — ONLY when the order is meaningful

Key takeaways

  1. 01Encoding turns categorical text into numbers models can use.
  2. 02One-hot: one 0/1 column per category — the safe default for unordered categories.
  3. 03Ordinal: maps to 0,1,2… — only for genuinely ordered categories.
  4. 04handle_unknown="ignore" prevents crashes on unseen categories at predict time.

Finished this chapter?

Mark it complete to track your progress through Scikit-learn.