One Hot Encode Categories in Python

Convert a list of categorical strings into one-hot encoded numeric vectors using pure Python and NumPy.

Easy Python 3.9+ Aug 9, 2026 ML engineering pipelines 13 views 0 copies

Requires third-party packages — install first
pip install numpy

Python code

17 lines
Python 3.9+
import numpy as np

categories = ["red", "green", "blue", "red", "blue", "green", "red"]

unique = sorted(set(categories))
lookup = {cat: i for i, cat in enumerate(unique)}

one_hot = []
for cat in categories:
    row = [0] * len(unique)
    row[lookup[cat]] = 1
    one_hot.append(row)

print("Categories:", categories)
print("Unique:", unique)
for cat, enc in zip(categories, one_hot):
    print(f"{cat:5} -> {enc}")

Output

stdout
Categories: ['red', 'green', 'blue', 'red', 'blue', 'green', 'red']
Unique: ['blue', 'green', 'red']
red   -> [0, 1, 0]
green -> [0, 0, 1]
blue  -> [1, 0, 0]
red   -> [0, 1, 0]
blue  -> [1, 0, 0]
green -> [0, 0, 1]
red   -> [0, 1, 0]

How it works

The code first extracts unique categories with set() and sorts them for a consistent order, creating a deterministic mapping from category to index. Each category is then mapped to a row of zeros with a single 1 at the position of that category's index. This converts categorical strings into numeric vectors that machine learning models can consume. The sorted order ensures the same encoding every run, which is important for reproducibility in training pipelines.

Common mistakes

  • Forgetting to sort the unique categories, leading to inconsistent indices across runs.
  • Assuming the input list is already numeric and skipping the explicit one-hot construction.
  • Using a dense array when a sparse representation would be more memory-efficient for many categories.

Variations

  1. Use `sklearn.preprocessing.OneHotEncoder` for a built-in, memory-efficient implementation.
  2. Convert to a NumPy array with `np.eye(len(unique))[indices]` for a more concise version.

Real-world use cases

  • Preparing categorical features like product categories or city names before feeding them into a logistic regression model.
  • Encoding user behavior segments (e.g., subscription tier) as binary columns for a recommendation system.
  • Transforming categorical columns in a pandas DataFrame for a gradient boosting model that requires numeric inputs.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from ML engineering pipelines

Related tutorials and quizzes for this topic.