How to ordinal encode categorical data in Python with sklearn
Convert job title categories into ordinal numeric labels using sklearn's OrdinalEncoder with explicit ordering.
pip install scikit-learn numpy
Python code
25 linesfrom sklearn.preprocessing import OrdinalEncoder
import numpy as np
# Mock data: small job title categories with known ordering
data = np.array([
["intern"],
["junior"],
["mid"],
["senior"],
["lead"]
])
# Define the ordinal order (lowest to highest)
categories = [["intern", "junior", "mid", "senior", "lead"]]
encoder = OrdinalEncoder(categories=categories)
encoded = encoder.fit_transform(data)
# Show original and encoded pairs for clarity
for original, numeric in zip(data.flatten(), encoded.flatten()):
print(f"{original:8s} -> {int(numeric)}")
# Demonstrate inverse transform
inverse = encoder.inverse_transform(encoded)
print("\nInverse check (first 3):", inverse.flatten()[:3].tolist())
Output
intern -> 0
junior -> 1
mid -> 2
senior -> 3
lead -> 4
Inverse check (first 3): ['intern', 'junior', 'mid']
How it works
OrdinalEncoder converts categorical strings into integer labels while preserving the order you specify in the categories parameter. By passing a list of lists, you define the exact mapping from lowest to highest. The fit_transform method both learns the categories and applies the encoding in one step. inverse_transform lets you reconstruct the original labels, which is useful for debugging or when you need to reverse predictions.
Common mistakes
- Forgetting to pass the ordered categories and relying on alphabetical order instead
- Applying fit_transform to the whole DataFrame instead of only the categorical columns
- Not using inverse_transform when you need to go back to original labels
- Mismatching the order of categories between training and inference data
Variations
- Use `LabelEncoder` for a single target column instead of features
- Write a custom manual mapping with a dictionary and `.map()` for simple cases
Real-world use cases
- Encoding job-level or seniority features before feeding them into a model that expects numeric input.
- Turning education levels, customer tiers, or risk ratings into ordered numbers for scoring pipelines.
- Preparing ordinal categorical columns in a feature engineering step for batch ML training jobs.
Sponsored
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.