Specify list of possible values for Pandas get_dummies
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
pd.get_dummies() creates dummy columns only for categories present in the data, which causes problems when test data has fewer categories than training data. To specify a fixed list of possible values, convert the column to a Categorical dtype with predefined categories before calling get_dummies(). This ensures consistent columns across training and test sets. For ML pipelines, prefer sklearn.preprocessing.OneHotEncoder which stores categories from fit() and applies them consistently during transform().
The Problem
The model trained on 3 columns receives 2 columns at prediction time, causing a shape mismatch error.
Fix 1: Use pd.Categorical with Fixed Categories
Convert the column to Categorical dtype with all possible values before encoding:
Both DataFrames now have identical columns.
Fix 2: Reindex After get_dummies
Apply get_dummies normally, then reindex to match training columns:
This also handles test data with unseen categories — extra columns are dropped, missing columns are added as zeros.
Fix 3: Use sklearn OneHotEncoder (Recommended for ML)
OneHotEncoder stores categories from fit() and applies them consistently:
handle_unknown='ignore' ensures unseen categories produce all-zero rows instead of errors.
Multiple Categorical Columns
Helper Function
drop_first for Multicollinearity
Common Pitfalls
- Not specifying categories on the test set:
get_dummies()on test data produces fewer columns if some categories are absent, causing column mismatch errors when feeding to a trained model. Always usepd.Categoricalorreindexto enforce consistent columns. - Forgetting
handle_unknown='ignore'withOneHotEncoder: If test data contains a category not seen duringfit(), the default behavior raises aValueError. Sethandle_unknown='ignore'to produce an all-zero row for unseen categories. - Using
get_dummiesin ML pipelines instead ofOneHotEncoder:get_dummiesdoes not have afit/transformAPI, so it cannot remember categories from training. For reproducible ML pipelines, usesklearn.preprocessing.OneHotEncoderinside aPipeline. - Passing the entire DataFrame to
pd.Categorical:pd.Categoricalworks on a single Series, not a DataFrame. Apply it column by column, or useOneHotEncoderwhich accepts multiple columns at once. - Not dropping the first dummy variable for linear models: Linear regression and logistic regression are sensitive to multicollinearity. Use
drop_first=Trueinget_dummiesordrop='first'inOneHotEncoderto remove one redundant column per feature.
Summary
- Convert columns to
pd.Categorical(col, categories=[...])beforeget_dummies()to ensure all categories appear - Use
reindex(columns=train_columns, fill_value=0)as an alternative alignment method - For ML pipelines, use
sklearn.preprocessing.OneHotEncoderwithhandle_unknown='ignore' - Use
drop_first=Trueto avoid multicollinearity in linear models - Store the category list from training and apply it to all future data consistently
Related reading
- Specifying and saving a figure with exact size in pixels
- Split / Explode a column of dictionaries into separate columns with pandas
- Split a dataset created by Tensorflow dataset API in to Train and Test?
- Split a large pandas dataframe
- Speed comparison with Project Euler C vs Python vs Erlang vs Haskell
- Speed of calculating powers in python
- Split a Pandas column of lists into multiple columns
- Split data directory into training and test directory with sub directory structure preserved
.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.