Skip to content
BENIBIX Learn

One-Hot Encoding

Also known as One-Hot Vector, Dummy Variables, One-Hot

Turns a word into a row of 0s with one 1. Now a model can read it.

Think of it like

It is like a row of light switches. Only one is on at a time.

Example

A house table has a city column with London, Paris or Tokyo. After one-hot encoding, a London house reads 1, 0, 0.

Why it matters

Most models only read numbers. This turns words into numbers without making up a false order.

Definition

One-hot encoding turns a word category into numbers a model can read. Each possible value gets its own column. The column for the right value holds a 1, and every other column holds a 0. So "red", "green" and "blue" become three columns. Using 1, 2 and 3 instead would wrongly say blue is bigger than red. Many values mean many columns, which is the cost.

Example code

python
import pandas as pd
pd.get_dummies(pd.Series(["London", "Tokyo"]), dtype=int)
#    London  Tokyo
# 0       1      0
# 1       0      1
Each city gets its own column. A 1 marks the city each row is in.
The city column becomes three columns, with a single 1 in each row.

Common mistake

Using it on a column with thousands of values, like postcodes. The table grows huge and sparse.

Key takeaways

  1. 1
    One column each. Every value gets its own column.
  2. 2
    A single 1. The rest are all 0.
  3. 3
    No false order. Blue is not bigger than red.

Learn it properly