Skip to content

Label Encoding

Label encoding converts categories into integers:

  • high → 2
  • For ordinal categories (where order matters):

    • low < medium < high
  • For tree models sometimes (but still be careful)

For nominal categories (no order):

  • city, color, country

Label encoding may trick models into believing an order exists.

Manual ordinal encoding
import pandas as pd
 
df = pd.DataFrame({"priority": ["low", "high", "medium", "low"]})
 
mapping = {"low": 0, "medium": 1, "high": 2}
df["priority_code"] = df["priority"].map(mapping)
 
print(df)

LabelEncoder is mainly designed for encoding target labels, not features.

LabelEncoder
from sklearn.preprocessing import LabelEncoder
 
le = LabelEncoder()
y = ["spam", "ham", "ham", "spam"]
print(le.fit_transform(y))
print(le.classes_)

Use:

  • One-hot encoding for nominal categories
  • Ordinal mapping for ordered categories
diagram Label encoding flow mermaid
Each distinct category is assigned an integer code; order is preserved only when the categories are truly ordinal.

Exercise 1 – Encode with a manual mapping

Section titled “Exercise 1 – Encode with a manual mapping”

Exercise 2 – Encode with scikit-learn’s LabelEncoder

Section titled “Exercise 2 – Encode with scikit-learn’s LabelEncoder”

Exercise 3 – Get codes from a category dtype

Section titled “Exercise 3 – Get codes from a category dtype”

For categories with no natural order, prefer One-Hot Encoding so the model doesn’t assume a ranking that isn’t real.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading