HOWTO · NumPy

One-Hot Encoding on NumPy Array in Python

This tutorial demonstrates how to perform one-hot encoding on a numpy array in python

On this page

One-hot encoding represents each category with a row of indicator values: the input label’s class column is 1, and the other class columns are 0. This is useful when a downstream tool expects numeric features or categorical targets in this form; it is not required by every model. This guide shows how to build those rows from a NumPy array and how the output differs across NumPy, scikit-learn, pandas, and Keras.

How one-hot encoding represents categories

A one-hot array has one row for each input item and one column for each class. The active column contains 1; every other column in that row contains 0. class_count sets the width. In this example, IDs 0 through 3 name the complete class set, so the result has four columns. Run this example:

import numpy as np

ids = np.array([1, 0, 3])
class_count = 4
rows = np.zeros((ids.size, class_count), dtype=int)
rows[np.arange(ids.size), ids] = 1
print(rows)
[[0 1 0 0]
 [1 0 0 0]
 [0 0 0 1]]

The inputs here are integer class IDs, not arbitrary category names. Each ID must be a valid column index from 0 up to (but not including) class_count. Choose that count from the full class set used by the task, including classes that might not appear in a particular sample. Using only the largest observed ID can omit a known class when it is absent from the current data. For labels such as "cat" or "blue", first map each category to a stable integer ID, or use an encoder that accepts category labels directly.

Create one-hot rows with NumPy indexed assignment and numpy.eye()

Indexed assignment is useful when the desired width is known: allocate a matrix with one row per label and one column per class, then set one position in each row. The code above uses this approach. Its result is a NumPy integer array, and the row order follows the input order. Keep the ID-to-category mapping alongside the array so each output column retains its meaning.

numpy.eye() offers a compact alternative. It creates an identity matrix, where each row has one active column; indexing that matrix by the ID array selects the required rows. Pass the same explicit class count so the matrix includes the full class set, even if some IDs are not observed. Both approaches assume nonnegative integer IDs in the permitted range. If labels are strings, negative numbers, or sparse identifiers such as 10 and 40, map them to consecutive IDs first rather than using those values directly as array positions.

import numpy as np

ids = np.array([1, 0, 3])
class_count = 4
rows = np.eye(class_count, dtype=int)[ids]
print(rows)
[[0 1 0 0]
 [1 0 0 0]
 [0 0 0 1]]

Encode labels with scikit-learn’s LabelBinarizer

Use LabelBinarizer when you want an encoder that learns a class-to-column mapping and applies it consistently to later data. Fit it on the complete training class set, then reuse that fitted encoder to transform labels. Unlike direct NumPy indexing, it accepts strings as well as integers. With four fitted classes, a multi-class transformation has one column per class; binary classification instead returns one column, so the output width depends on the class configuration.

In a scikit-learn project, call encoder.fit(class_labels) and encoder.transform(labels); classes_ gives the column order. The example uses LabelBinarizer when scikit-learn is installed; otherwise, its standard-library fallback demonstrates the same mapping so the example remains runnable:

class_labels = ["blue", "green", "red", "yellow"]
labels = ["green", "red", "blue"]
try:
    from sklearn.preprocessing import LabelBinarizer
    encoder = LabelBinarizer()
    encoder.fit(class_labels)
    rows = encoder.transform(labels).tolist()
except ModuleNotFoundError:
    class_to_column = {label: index for index, label in enumerate(class_labels)}
    rows = []
    for label in labels:
        row = [0] * len(class_labels)
        row[class_to_column[label]] = 1
        rows.append(row)
print(rows)
[[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]

Create indicator columns with pandas.get_dummies()

pandas.get_dummies() is convenient when the next step uses a DataFrame and named category columns are helpful. It creates one indicator column for each category observed in the supplied values, with one row per input item. The output remains a pandas DataFrame, unlike the NumPy arrays above. By default, a category absent from the input does not get a column, so use an explicit category definition or reindex the result when columns must match a separately known class set across datasets.

import numpy as np
import pandas as pd

labels = np.array(["green", "red", "blue"])
indicators = pd.get_dummies(labels)
print(indicators)
    blue  green    red
0  False   True  False
1  False  False   True
2   True  False  False

This method accepts category labels directly and avoids making a numeric mapping yourself. Its columns follow the categories represented in the data, so retain or define the column order when combining results from separate batches. Choose it for tabular workflows; choose a NumPy array or fitted encoder when the receiving API expects those forms.

Create one-hot rows with Keras to_categorical()

Keras to_categorical() converts integer class IDs into a dense array of one-hot rows. Supply num_classes explicitly using the size of the full class set. The number of input labels is not the class count: for example, three observations can belong to a four-class problem. IDs must be nonnegative integers below that count, just as with direct NumPy indexing.

Pass the full class count explicitly so each row has four columns. The example calls Keras to_categorical() when Keras is installed; its standard-library fallback keeps the same demonstration runnable when the package is unavailable:

ids = [1, 0, 3]
class_count = 4
try:
    from keras.utils import to_categorical
    rows = to_categorical(ids, num_classes=class_count).tolist()
except ModuleNotFoundError:
    rows = []
    for class_id in ids:
        row = [0.0] * class_count
        row[class_id] = 1.0
        rows.append(row)
print(rows)
[[0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]]

Keras returns a dense array suitable for code that consumes categorical targets. It uses numeric IDs rather than category strings; map arbitrary labels to a stable integer scheme before calling it. Use this option when the next step is a Keras workflow, LabelBinarizer when a fitted label-to-column mapping is useful, get_dummies() when a DataFrame is the preferred result, and direct NumPy operations when integer IDs and an array are already a natural fit.