Home Knowledge Base Label Encoding

Label Encoding is a simple categorical encoding technique that assigns a unique integer to each category — mapping "Red" → 0, "Green" → 1, "Blue" → 2 — providing a compact representation that is appropriate for ordinal data (Low < Medium < High) and tree-based models (which split on thresholds regardless of ordinal meaning), but problematic for linear models and distance-based algorithms that interpret the integers as having mathematical relationships (2 > 1 > 0 implies an ordering that may not exist).

What Is Label Encoding?

Label Encoding Example

OriginalEncoded
"Cat"0
"Dog"1
"Fish"2
"Cat"0
"Fish"2

When to Use Label Encoding

ScenarioSafe?Reason
Ordinal features (Low/Medium/High)Yes ✓Order is meaningful
Tree-based models (Random Forest, XGBoost)Yes ✓Trees don't assume ordinal meaning, they just find optimal split thresholds
Linear Regression with nominal featuresNo ✗Model learns weight × integer, implying order
KNN / SVM with nominal featuresNo ✗Distance calculations treat integers as ordered
Neural Networks with nominal featuresNo ✗Embedding layers or one-hot are preferred
Target variable encodingYes ✓sklearn requires numeric targets for classification

Label Encoding vs Alternatives

Encoding# ColumnsOrdinal AssumptionHigh CardinalityBest For
Label Encoding1 (same column)Yes (implied)Handles wellOrdinal features, tree models, target labels
One-Hot EncodingK (one per category)NoExplodes dimensionalityLinear models, neural networks
Target Encoding1 (continuous)NoHandles wellHigh-cardinality + supervised learning
Ordinal Encoding1 (explicit order mapping)Yes (explicit)Handles wellWhen you define the order

Python Implementation

from sklearn.preprocessing import LabelEncoder, OrdinalEncoder

# LabelEncoder (for target variable / single column)
le = LabelEncoder()
y_encoded = le.fit_transform(["cat", "dog", "fish", "cat"])
# [0, 1, 2, 0]

# OrdinalEncoder (for features with custom order)
oe = OrdinalEncoder(categories=[["low", "medium", "high"]])
X_encoded = oe.fit_transform(df[["satisfaction"]])

Label Encoding is the compact, memory-efficient encoding for ordinal features and tree-based models — providing a single-column integer representation that preserves ordering information, with the critical caveat that it should never be used for nominal (unordered) categories in linear or distance-based models where the implied ordinal relationship corrupts the model's learning.

label encodingordinalconvert

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.