Sub topic 4
How one-hot encoding works
This chapter assumes you know basic pandas DataFrames, NumPy arrays, and what a feature matrix is. It explains the idea behind one-hot encoding and builds it by hand before you use library tools in later chapters.
The core idea
A model such as linear regression or logistic regression multiplies each feature by a weight. A text label like "red" cannot be multiplied, and an integer code like red = 2 would claim that red is twice green. One-hot encoding avoids both problems.
One-hot encoding replaces one categorical column with one binary column per category. In each row, exactly one of those columns is 1 (the "hot" one) and the rest are 0. The 0/1 columns are called indicator columns.
Take a color column with the values red, green, blue, green:
| color (original) | color_blue | color_green | color_red |
|---|---|---|---|
| red | 0 | 0 | 1 |
| green | 0 | 1 | 0 |
| blue | 1 | 0 | 0 |
| green | 0 | 1 | 0 |
Each category now has its own weight. The model can learn that green rows behave differently from red rows without assuming any order or distance between colors.
Building it by hand
The procedure has two steps. First, collect the distinct categories and fix their order. Second, for each row, put a 1 in the column that matches its label.
import numpy as np
colors = ["red", "green", "blue", "green"]
categories = sorted(set(colors))
index = {c: i for i, c in enumerate(categories)}
onehot = np.zeros((len(colors), len(categories)), dtype=int)
for row, c in enumerate(colors):
onehot[row, index[c]] = 1
print(categories)
print(onehot)The output is:
['blue', 'green', 'red']
[[0 0 1]
[0 1 0]
[1 0 0]
[0 1 0]]The first step, learning the category list, is the part that matters most in practice. The category list is a property of your training data. If you rebuild it separately for new data, the columns can change order or count. The chapter on fitting and transforming covers this.
The same result with pandas
pd.get_dummies does both steps in one call:
import pandas as pd
df = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
encoded = pd.get_dummies(df, columns=["color"], dtype=int)
print(encoded) color_blue color_green color_red
0 0 0 1
1 0 1 0
2 1 0 0
3 0 1 0The original color column is gone. Each new column is named <original>_<category>, and the columns appear in sorted category order. Passing dtype=int gives 0/1 integers. Recent pandas versions return booleans by default.
What changes in the data
One-hot encoding widens the feature matrix. A column with k categories becomes k columns, so a city feature with 200 cities adds 200 columns. Most of the entries are zeros. For small feature sets this is harmless. For features with many categories it costs memory and can hurt some models, which is why later chapters cover sparse output and rare categories.
Exercise
A size column has the values small, medium, large, medium. After one-hot encoding, how many columns does it produce, and what is the row for the first "medium" value? Assume the columns are in alphabetical order.
Show answer
It produces 3 columns, in the order sizelarge, sizemedium, size_small. The first "medium" row is [0, 1, 0].