One Hot Encoding in Python with pandas and scikit-learn
Turn text categories into 0/1 columns, and keep the same columns for new data with OneHotEncoder.
- pd.get_dummies for quick encoding
- OneHotEncoder with fit and transform
- handle_unknown="ignore" for new categories
One column per category
The problem
Columns such as city, colour or country hold words, and models only understand numbers. Replacing them with 0, 1, 2 would invent an order (Tokyo > Paris) that does not exist.
Think of it like this
One hot encoding is like a row of light switches, one per city. For each row exactly one switch is on, the one for its city, and all the others are off. A city the switchboard has never seen leaves every switch off.
encoder.fit(train[["city"]])🔌 Install one switch per known cityget_feature_names_out()🏷️ The labels on the switchestransform(test[["city"]])💡 Turn on the switch for each row's cityhandle_unknown="ignore"🌑 Unknown city: all switches offOne hot encoding replaces a category column with one 0/1 column per category; each row has a 1 in the column of its own category and 0 elsewhere.
Key points
pd.get_dummiesbuilds the columns from the values it finds, so train and test can get different columns.OneHotEncoderlearns the categories withfitand always produces the same columns withtransform.handle_unknown="ignore"turns an unseen category (Oslo) into all zeros instead of an error.sparse_output=Falsereturns a normal array instead of a sparse matrix.
When should you use it?
- Feeding text categories to scikit-learn models.
- Keeping training and prediction data in the same format.
- Inside a ColumnTransformer next to scaled numeric columns.
When not to use it
- Categories with a real order (small, medium, large): OrdinalEncoder keeps it.
- Columns with thousands of distinct values: the table becomes huge; group rare values or use another encoding.
Example code
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"city": ["Paris", "Tokyo", "Lima", "Tokyo"], "size": [3, 1, 2, 2]})
test = pd.DataFrame({"city": ["Lima", "Oslo"], "size": [1, 3]})
# pandas: quick, but the columns depend on which values appear
print(pd.get_dummies(train, columns=["city"], dtype=int))
print(list(pd.get_dummies(test, columns=["city"], dtype=int).columns))
# scikit-learn: learns the categories once and reuses them
encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
encoder.fit(train[["city"]])
print(encoder.get_feature_names_out().tolist())
print(encoder.transform(test[["city"]]).astype(int).tolist()) # Oslo is unknown -> all zeros
Result of running the code
size city_Lima city_Paris city_Tokyo
0 3 0 1 0
1 1 0 0 1
2 2 1 0 0
3 2 0 0 1
['size', 'city_Lima', 'city_Oslo']
['city_Lima', 'city_Paris', 'city_Tokyo']
[[1, 0, 0], [0, 0, 0]]
Code explanation
pd.get_dummies replaces the city column with one 0/1 column per city found in train. Run on test, it builds different columns (city_Lima and city_Oslo), so a model trained on the first table could not read the second. OneHotEncoder learns the three categories from train once, get_feature_names_out shows them, and transform always produces those same three columns. Because of handle_unknown="ignore", the unseen city Oslo becomes [0, 0, 0] instead of raising an error.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Encoding train and test separately with get_dummies
Each call builds columns from its own values, so the tables no longer match.
pd.get_dummies(test, columns=["city"])
encoder.transform(test[["city"]])
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challengesTools for this lesson
- Tokenization: Vocabulary, One-Hot and Byte Pair Encoding in PythonTurn text into numbers the way language models do: build a vocabulary, one-hot encode words and learn subword tokens with BPE.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.