Handling Messy Data · Lesson 3 of 7
Categorical variables
What is a categorical variable
A categorical variable takes one of a limited set of values. A survey asking how often you eat breakfast ("Never", "Rarely", "Most days", "Every day") is categorical. So is car brand ("Honda", "Toyota", "Ford"), or our region column ("Urban", "Rural"). Models work with numbers, so feeding them text causes an error. You must convert categories to numbers first.
Ordinal or nominal?
Before encoding, ask whether the categories have a natural order:
- Ordinal: there is a clear ranking. "Never" < "Rarely" < "Most days" < "Every day". Education level is another example.
- Nominal: there is no ranking. "Honda" is not more or less than "Toyota"; "Urban" is not more or less than "Rural".
This decides which encoding fits best.
Three approaches
1. Drop the categorical columns. Simplest, but you lose whatever information they held. Only sensible if the column was not useful.
2. Ordinal encoding. Give each category an integer: Never=0, Rarely=1, Most days=2, Every day=3. This builds in an order, so it suits ordinal variables, and it works well with tree-based models like random forests.
3. One-hot encoding. Make a new True/False column for each category (a "region_Urban" column and a "region_Rural" column). It assumes no order, so it suits nominal variables. It is the usual safe default, but avoid it when a column has many categories (roughly more than 15), since it creates a column for each one.
Compare them yourself
Which to use
As a rule: one-hot encoding is the safe default for nominal data with few categories, ordinal encoding when the categories have a real order (and you are using a tree-based model), and dropping only when the column is genuinely useless. On a small dataset like this the scores will be close, but dropping a useful column usually performs worst on real data.
Exercise
One-hot encode the "region" column of df with pd.get_dummies. Store the result in encoded.