Machine Learning with scikit-learn

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.

  • Intermediate
  • 2 min read
  • 1 runnable example
What you'll learn
  • pd.get_dummies for quick encoding
  • OneHotEncoder with fit and transform
  • handle_unknown="ignore" for new categories
city -> [Lima, Paris, Tokyo]
Paris
0
1
0
Tokyo
0
0
1
Oslo
0
0
0

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.

From light switches to code
encoder.fit(train[["city"]])🔌 Install one switch per known city
get_feature_names_out()🏷️ The labels on the switches
transform(test[["city"]])💡 Turn on the switch for each row's city
handle_unknown="ignore"🌑 Unknown city: all switches off
One switch per category, exactly one on.
In one sentence

One 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

  1. pd.get_dummies builds the columns from the values it finds, so train and test can get different columns.
  2. OneHotEncoder learns the categories with fit and always produces the same columns with transform.
  3. handle_unknown="ignore" turns an unseen category (Oslo) into all zeros instead of an error.
  4. sparse_output=False returns 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

Open in editor →
main.py
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
Get a Run button for this example

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.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Encoding train and test separately with get_dummies

Each call builds columns from its own values, so the tables no longer match.

Problem
pd.get_dummies(test, columns=["city"])
Fix
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 challenges

Tools for this lesson