Learning path: Prepare Data for a Machine Learning Model · Step 3 of 7
Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
Models only understand numbers. Encode T-shirt sizes with OrdinalEncoder, colours with OneHotEncoder, avoid the dummy variable trap, handle a colour the encoder never saw, tame a date with 3,436 values, and encode the answer with LabelEncoder.
What you will learn
- Turn ordered categories into ordered numbers with OrdinalEncoder and your own order
- One-hot encode unordered categories, and drop one column with drop="first" for linear models
- Stop new categories from crashing a model with handle_unknown="ignore"
- Know when a column has too many categories, and use LabelEncoder only for the target
Before you start
- Reading a CSV with pandas
- Train-Test Split and Data Leakage
Machine learning models only understand numbers. Words like "Canberra", "red" or "XL" have to become numbers first. The trick is to do it without telling the model something false.
Think about T-shirts. Sizes have an order: S, M, L, XL. Turn them into 0, 1, 2, 3 and small-to-big stays small-to-big. Colours don't: is green bigger than red? Of course not. Numbering them 1, 2, 3 would invent an order the model would believe. So each colour gets its own tick box instead.
That's the whole idea. Ordered categories become ordered numbers, and unordered ones get one tick box each. Let's do both in scikit-learn.
A small table to start
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder
shirts = pd.DataFrame({
"size": ["S", "M", "L", "M", "XL"],
"colour": ["red", "blue", "green", "blue", "red"]})
print(shirts)
size colour
0 S red
1 M blue
2 L green
3 M blue
4 XL red
Five shirts. Size has an order, colour doesn't.
OrdinalEncoder keeps the order
For size, use OrdinalEncoder and pass the order yourself in categories:
order = [["S", "M", "L", "XL"]]
ordinal = OrdinalEncoder(categories=order)
print(ordinal.fit_transform(shirts[["size"]]).ravel())
[0. 1. 2. 1. 3.]
S, M, L, M, XL became 0, 1, 2, 1, 3. The order is kept. If you leave out categories, the encoder sorts the values alphabetically, and L would come before M. Always give it the real order.
OneHotEncoder gives each colour a tick box
onehot = OneHotEncoder(sparse_output=False)
print(onehot.fit_transform(shirts[["colour"]]))
print(onehot.get_feature_names_out())
[[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]]
['colour_blue' 'colour_green' 'colour_red']
sparse_output=False just gives a plain array we can read. One colour column became three columns, one per colour, and every row has a single 1 in its own colour.
One column is always spare: drop="first"
Look again. If green is 0 and red is 0, the shirt can only be blue. So the blue column adds nothing new. For linear models this perfect copy is called the dummy variable trap, and it can make the results unstable. drop="first" removes the first column:
dropped = OneHotEncoder(sparse_output=False, drop="first")
print(dropped.fit_transform(shirts[["colour"]]))
print(dropped.get_feature_names_out())
[[0. 1.]
[0. 0.]
[1. 0.]
[0. 0.]
[0. 1.]]
['colour_green' 'colour_red']
Now blue is simply the row where both columns are 0. Two columns carry the same information as three. Tree models don't mind the extra column, but for linear models drop="first" is a good habit.
A colour the encoder never saw
In the real world, new values turn up. A new shirt arrives in purple, which wasn't in the training data:
new = pd.DataFrame({"colour": ["purple"]})
try:
onehot.transform(new)
except ValueError as err:
print(type(err).__name__)
ValueError
The default encoder crashes. Set handle_unknown="ignore" and it won't:
safe = OneHotEncoder(
sparse_output=False, handle_unknown="ignore")
safe.fit(shirts[["colour"]])
print(safe.transform(new))
[[0. 0. 0.]]
Purple becomes all zeros, and the model carries on. For a deployed model, this one setting saves a lot of pain.
Too many categories means too many columns
One-hot has a weakness: a column with many different values adds that many columns. Count them first with nunique(), on the Rain in Australia table:
weather = pd.read_csv("weatherAUS.csv")
print(weather["Location"].nunique())
print(weather["Date"].nunique())
49
3436
Location has 49 values, so one-hot adds 49 columns. That's fine. But Date has 3,436 different values. One-hot would add 3,436 columns, almost all zeros, and each one is basically a single day. Take something meaningful out of the date instead, like the month:
dates = pd.to_datetime(weather["Date"])
print(dates.dt.month.nunique())
12
Twelve values, and it carries the season. That's a column you can one-hot. Never one-hot a raw date.
LabelEncoder is for the answer column
The answer, RainTomorrow, is No or Yes. LabelEncoder is made for this column, the y. We split first, so it learns only from the training answers:
y = weather["RainTomorrow"]
y_train, y_test = train_test_split(
y, test_size=0.2, stratify=y, random_state=42)
le = LabelEncoder()
y_train_num = le.fit_transform(y_train)
print(le.classes_, y_train_num[:5])
['No' 'Yes'] [0 0 0 1 0]
No became 0 and Yes became 1, and classes_ tells you which is which.
Never use LabelEncoder on input columns. It numbers values alphabetically, which invents an order. For inputs, use OrdinalEncoder (real order) or OneHotEncoder (no order).
Common mistakes
- OrdinalEncoder without
categories: you get alphabetical order, so L comes before M. - Numbering unordered categories 0, 1, 2 with an ordinal or label encoder.
- No
handle_unknown="ignore"on a model that will meet new values. - One-hot encoding a raw date or an id column with thousands of values.
- Fitting encoders on all rows. Like every step, fit on the train rows and only transform the test rows.
Quick recap
| Column type | Tool | Example |
|---|---|---|
| Ordered categories | OrdinalEncoder(categories=...) | S, M, L, XL to 0, 1, 2, 3 |
| Unordered categories | OneHotEncoder | colour to 3 columns |
| Linear models | drop="first" | 3 colour columns to 2 |
| New values at prediction time | handle_unknown="ignore" | purple to [0, 0, 0] |
| Too many values | extract a feature | Date 3,436 values, month 12 |
| The answer column only | LabelEncoder | No, Yes to 0, 1 |
Try it yourself
One-hot encode weather["Location"] after the split: fit on the train rows, then transform the test rows with handle_unknown="ignore". Print the shape. How many columns do you expect?
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
Next →Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Train-Test Split and Data Leakage: Split First, Learn After
Why the train-test split comes before everything else: an 80/20 split with stratify and random_state, a scaler that leaks test rows, and a column that secretly holds the answer. Shown on Rain in Australia.
Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
Count the blanks with isnull().sum(), see why dropna() would throw away 60% of the rows, and fill the gaps with SimpleImputer: median for numbers, most frequent for text, learned from the train rows only. Shown on Rain in Australia.
Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
Put features on the same scale so each one gets a fair say. StandardScaler and MinMaxScaler fitted on the train rows, the formula checked by hand, and a wine test where KNN jumps from 0.806 to 0.972 while a decision tree stays at 0.944.
Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
Pack imputing, encoding, scaling and the model into one scikit-learn Pipeline with two ColumnTransformer lanes. One fit on the train rows, 21 columns in, 115 out, 0.849 test accuracy, and a raw row with a blank predicted directly.