One Hot Encode Categories in Python
Convert a list of categorical strings into one-hot encoded numeric vectors using pure Python and NumPy.
pip install numpy
Python code
17 linesimport 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
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
- Use `sklearn.preprocessing.OneHotEncoder` for a built-in, memory-efficient implementation.
- 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
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.