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:
from sklearn.preprocessing import OneHotEncoderenc = OneHotEncoder(handle_unknown="ignore", sparse_output=False)X_enc = enc.fit_transform(X[["city"]])# "Pune"/"Delhi"/"Mumbai" → three 0/1 columns
Ordinal encoding
from sklearn.preprocessing import OrdinalEncoderenc = OrdinalEncoder(categories=[["low", "mid", "high"]])# maps to 0, 1, 2 — ONLY when the order is meaningful
Key takeaways
- 01Encoding turns categorical text into numbers models can use.
- 02One-hot: one 0/1 column per category — the safe default for unordered categories.
- 03Ordinal: maps to 0,1,2… — only for genuinely ordered categories.
- 04handle_unknown="ignore" prevents crashes on unseen categories at predict time.
