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.

Easy Python 3.9+ Aug 9, 2026 ML engineering pipelines 15 views 0 copies

Requires third-party packages — install first
pip install scikit-learn numpy

Python code

25 lines
Python 3.9+
from 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

stdout
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

  1. Use `LabelEncoder` for a single target column instead of features
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from ML engineering pipelines

Related tutorials and quizzes for this topic.