How to encode a categorical variable in sklearn?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Scikit learn models require numeric input, so categorical columns must be encoded before training. The correct encoder depends on whether categories are nominal or ordered and whether the model can handle sparse high dimensional features. A robust solution also handles unseen values during inference.
Choose the Right Encoder for the Feature Type
For unordered categories such as city or color, one hot encoding is usually the safest default. It creates one binary column per category and avoids fake numeric ordering.
For ordered categories such as small, medium, large, use ordinal encoding only when that order is meaningful and model behavior matches it.
Use ColumnTransformer in a Pipeline
In real projects, you have mixed numeric and categorical columns. ColumnTransformer lets you define preprocessing once and keep it tied to the model in a single pipeline.
This pattern prevents train test leakage because encoding is learned only from training data inside the pipeline.
Handle High Cardinality Carefully
A feature with thousands of unique values can explode dimensionality with one hot encoding. Consider feature hashing, target encoding with leakage safeguards, or grouping rare categories into an other bucket.
When you serve models, preserve the fitted encoder object and reuse it at inference time. Re fitting encoders online can reorder columns and break model inputs.
For tree based libraries that accept categorical types directly, check native support before encoding by hand, but for core scikit learn estimators, explicit encoding remains standard.
Persist and Reuse the Same Encoder in Production
Training and inference must share the exact same preprocessing object. The easiest approach is to save the fitted pipeline as one artifact and load it in your prediction service. This guarantees the encoded column layout is identical across environments.
When data contracts evolve, add compatibility tests that compare prediction input schemas between current and previous model versions. That keeps encoder changes from breaking downstream consumers unexpectedly.
Common Pitfalls
- Applying label encoding to unordered categories: this injects false ranking.
- Fitting encoder before train test split: this leaks category information from test data.
- Forgetting
handle_unknown="ignore": prediction fails on unseen categories. - Rebuilding feature columns manually: column order drift leads to wrong predictions.
- Dropping too many categories for convenience: model loses predictive signal.
Summary
- Use one hot encoding for nominal categories and ordinal encoding only for real order.
- Wrap preprocessing and model in a pipeline to avoid leakage.
- Configure unknown category handling for stable inference.
- Plan for high cardinality features early to control feature size.
- Persist the fitted preprocessing pipeline with the model artifact.
- Version your preprocessing artifacts alongside model versions so rollback and reproducibility remain straightforward during incident response.
Related reading
- How to encode dependency path as a feature for classification?
- How to engineer features for machine learning
- How to enlarge a tensorduplicate value in tensorflow?
- How to estimate the progress of a GridSearchCV from verbose output in Scikit-Learn?
- How to estimate how much memory a Pandas' DataFrame will need?
- How to explore a decision tree built using scikit learn
- How to evolve weights of a neural network in Neuroevolution?
- How to exactly add L1 regularisation to tensorflow error function
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.