How to one-hot encode categorical data in Python
One-hot encoding is the most common way to turn categorical data — text values with no inherent number, such as colour names — into numeric columns that a Machine Learning model can use. Most algorithms, from regression to decision trees, only work with numbers. If we leave the categories as text, training fails; if we replace them with 1, 2 and 3, we create a false order between them. One-hot encoding solves both problems at once and is simple to apply in Python with scikit-learn.
Prerequisites
- Python 3.8 or later installed.
- The
scikit-learnandpandaslibraries. - Basic knowledge of pandas DataFrames.
- A dataset with at least one text (categorical) column.
Step 1: Understand the problem
Imagine a table with a "cor" (colour) column. The values "azul", "verde" and "vermelho" (blue, green and red) have no mathematical meaning, and we cannot simply swap them for 1, 2 and 3 — that would make the model think "vermelho" (3) is greater than "azul" (1), which makes no sense. Let's create this example:
import pandas as pd
df = pd.DataFrame({
"cor": ["azul", "verde", "vermelho", "azul"],
"preco": [10, 15, 20, 12]
})
print(df)
The cor column is categorical; the preco column is already numeric and needs no treatment.
Step 2: Import the OneHotEncoder
scikit-learn ships a ready-made class for this task: the OneHotEncoder. If you don't have the libraries yet, install them in the terminal with pip install scikit-learn pandas. Then import the encoder in your script:
from sklearn.preprocessing import OneHotEncoder
Step 3: Apply one-hot encoding
We create the encoder and apply it to the categorical column. The sparse_output=False parameter returns a normal array (easier to read) and handle_unknown="ignore" prevents errors if categories the encoder didn't see during training appear later.
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
codificado = encoder.fit_transform(df[["cor"]])
print(codificado)
The fit_transform method does two things: it learns which categories exist (fit) and turns them into numbers (transform). The result is a matrix where each category becomes a column with values 0 or 1. Each row has a single 1 — hence the name "one-hot".
Step 4: Join the columns to the DataFrame
The matrix on its own is hard to read. Let's give it column names with get_feature_names_out() and join it to the original DataFrame, dropping the text column:
nomes = encoder.get_feature_names_out(["cor"])
df_codificado = pd.DataFrame(codificado, columns=nomes)
resultado = pd.concat([df.drop(columns=["cor"]), df_codificado], axis=1)
print(resultado)
You now have a fully numeric DataFrame, with columns such as cor_azul, cor_verde and cor_vermelho, ready to train a model.
Step 5: A quick pandas alternative
For quick exploration, pandas offers get_dummies, which does the same in a single line:
resultado_rapido = pd.get_dummies(df, columns=["cor"])
print(resultado_rapido)
It is very handy for one-off analysis. Even so, in Machine Learning projects the OneHotEncoder is preferable, because it remembers the categories seen during training and applies exactly the same ones to the test data, avoiding different columns between datasets. Tip: to avoid redundancy between columns, you can use OneHotEncoder(drop="first"), which removes the first category.
Check the result
Confirm that the final DataFrame no longer contains text: every column should be numeric. You should see one column per distinct colour, with 0 or 1 in each row. A good check is to sum each row of the colour columns — the total should always be 1, because each record belongs to exactly one category. Test it with df_codificado.sum(axis=1) and confirm that all values are 1.
Conclusion
You have just converted categorical data into numeric columns with one-hot encoding, using scikit-learn's OneHotEncoder and the pandas get_dummies alternative. The natural next step is to plug this encoder into a Pipeline, so you apply preprocessing and model training in one go. Which categorical columns in your dataset need to be encoded?