Sub topic 12
Encoding categoricals for machine learning
Most machine learning models need numbers, not labels. This chapter shows two ways to turn a pandas categorical column into numeric input: integer codes and one-hot encoding. It assumes you know how categories and codes work (see "Categories, codes, and the .cat accessor") and how ordered categoricals behave.
Two encodings, two meanings
A categorical column already stores integer codes. That makes it tempting to feed the codes straight into a model. Whether that is correct depends on what the codes imply.
- Integer codes tell the model that the values have an order and that the gaps between them are equal. This suits ordered data such as small, medium, large.
- One-hot encoding creates one 0/1 column per category. It says nothing about order, so it suits unordered data such as colors or cities.
Linear models, neural networks, and distance-based models treat codes as quantities. A tree-based model can split on codes without much harm, but one-hot columns are still the safer default for unordered data.
Encoding ordered data with codes
The codes follow the order of the categories. Declare the order explicitly so that the codes match the real ranking.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.DataFrame({"size": pd.Series(["small", "large", "medium", "small"], dtype=size_type)})
df["size_code"] = df["size"].cat.codes
print(df)The output shows small as 0, medium as 1, and large as 2. If you had let pandas infer the categories, they would be sorted alphabetically (large, medium, small) and the codes would run in the wrong order.
One-hot encoding with get_dummies
pd.get_dummies creates one indicator column per category. Because it reads the categories from the dtype, a category that never appears in the data still gets a column, filled with zeros.
import pandas as pd
color_type = pd.CategoricalDtype(["red", "green", "blue"])
df = pd.DataFrame({"color": pd.Series(["red", "blue", "red"], dtype=color_type)})
dummies = pd.get_dummies(df["color"], prefix="color", dtype=int)
print(dummies)
print(dummies.columns.tolist())The result has the columns color_red, color_green, and color_blue, in category order. The green column is all zeros because no row has that value.
Passing dtype=int gives 0 and 1. Recent pandas versions return booleans by default, and some libraries expect numbers.
Keeping training and test columns aligned
A common error is encoding the training set and the test set separately. If the test set lacks a value, plain get_dummies on object columns produces fewer columns, and the model fails or silently misaligns features.
Using one shared CategoricalDtype avoids this. Both sets then carry the same categories, so both produce the same columns in the same order.
import pandas as pd
color_type = pd.CategoricalDtype(["red", "green", "blue"])
train = pd.Series(["red", "green", "blue", "red"], dtype=color_type)
test = pd.Series(["blue", "blue"], dtype=color_type)
train_x = pd.get_dummies(train, prefix="color", dtype=int)
test_x = pd.get_dummies(test, prefix="color", dtype=int)
print(train_x.columns.tolist() == test_x.columns.tolist()) # TrueDefine the dtype once from the training data, save it, and apply it to every later dataset.
Missing values
A missing value has the code -1. If you pass cat.codes to a model, -1 looks like a real category that ranks below the first one. Handle missing values before encoding. You can fill them with a chosen category, or check for -1 and decide how to treat it.
get_dummies gives a missing row zeros in every column by default. Set dummy_na=True if you want a separate column that flags missing values.
Exercise
Exercise
A column "grade" holds the values "low", "medium", and "high" with no declared order. You call df["grade"].astype("category").cat.codes and pass the result to a linear regression. Give two problems with this and one fix.
Show answer
First, the categories are sorted alphabetically (high, low, medium), so the codes are 0, 1, 2 for high, low, medium. That order does not match the real ranking. Second, a linear model reads the codes as equally spaced quantities, so it assumes a numeric relationship that may not exist. Fix: declare pd.CategoricalDtype(["low", "medium", "high"], ordered=True) and use its codes if the ranking is meaningful, or use pd.get_dummies if it is not.