Create a zeroed array b with enough columns, i.e. a.max() + 1.
Then, for each row i, set the a[i]th column to 1.

>>> a = np.array([1, 0, 3])
>>> b = np.zeros((a.size, a.max() + 1))
>>> b[np.arange(a.size), a] = 1

>>> b
array([[ 0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.]])
Answer from YXD on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › how-to-convert-an-array-of-indices-to-one-hot-encoded-numpy-array
How to convert an array of indices to one-hot encoded NumPy array - GeeksforGeeks
July 23, 2025 - This results in a one-hot encoded representation of the original array, where each unique value in 'arr' corresponds to a unique column in 'encoded_arr', and a 1 is placed in the column corresponding to the value in 'arr'.
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.OneHotEncoder.html
OneHotEncoder — scikit-learn 1.9.1 documentation
The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka ‘one-of-K’ or ‘dummy’) encoding scheme.
🌐
GitHub
gist.github.com › pemagrg1 › 4a9141f79e91bfc0307cc13ad03e8152
one hot encoding using numpy · GitHub
one hot encoding using numpy. GitHub Gist: instantly share code, notes, and snippets.
🌐
YouTube
youtube.com › codetime
numpy array one hot encoding - YouTube
Download 1M+ code from https://codegive.com one-hot encoding is a crucial technique in data preprocessing, particularly when working with categorical variab...
Published: November 18, 2024
Views: 0
Find elsewhere
🌐
Educative
educative.io › answers › how-to-convert-an-array-of-indices-to-one-hot-encoded-numpy-array
How to convert an array of indices to one-hot encoded NumPy array
One-hot encoding creates a 2-D array whose number of rows is equal to the size of the original array and number of columns is equal to the max element in the 1-D array added to
🌐
OpenAI
blog.gopenai.com › what-is-one-hot-encoding-how-to-use-one-hot-encoding-f1edf7d4caaf
What is one hot encoding? How to use one hot encoding? | by Sunny Kumar | GoPenAI
January 5, 2024 - Let us try converting a sample categorical array to one hot encoding. Import the necessary library . For this tutorial we will be using sklearn library and numpy.
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › 10 numpy one-liners to simplify feature engineering
10 NumPy One-Liners to Simplify Feature Engineering - MachineLearningMastery.com
July 8, 2025 - One-hot encoding is essential for handling categorical variables in machine learning. While pandas provides convenient methods, pure NumPy implementations are faster and more memory-efficient for large datasets.
🌐
DataCamp
datacamp.com › tutorial › one-hot-encoding-python-tutorial
What Is One Hot Encoding and How to Implement It in Python | DataCamp
June 26, 2024 - This example demonstrates how to fit the encoder on the training data and then transform both training and test data, including handling categories that were not present in the training set. from sklearn.preprocessing import OneHotEncoder import numpy as np # Training data X_train = [['Red'], ['Green'], ['Blue']] # Creating the encoder with handle_unknown='ignore' enc = OneHotEncoder(handle_unknown='ignore') # Fitting the encoder to the training data enc.fit(X_train) # Transforming the training data X_train_encoded = enc.transform(X_train).toarray() print("Encoded training data:") print(X_train_encoded) # Test data with an unknown category 'Yellow' X_test = [['Red'], ['Yellow'], ['Blue']] # Transforming the test data X_test_encoded = enc.transform(X_test).toarray() print("Encoded test data:") print(X_test_encoded)
🌐
AI Mind
pub.aimind.so › one-hot-encoding-for-machine-learning-with-python-and-scikit-learn-c6d8e1173760
One-Hot Encoding for Machine Learning (with Python and Scikit-Learn) | by Francesco Franco | AI Mind
November 22, 2024 - We can then use Scikit-learn for converting the values into a one-hot encoded array, because it offers the sklearn.preprocessing.OneHotEncoder module. We first import the numpy module for converting a Python list into a NumPy array, and the preprocessing module from Scikit-learn.
🌐
JanBask Training
janbasktraining.com › community › devops › convert array of indices to 1-hot encoded numpy array
Convert array of indices to 1-hot encoded numpy array | JanBask Training Community
July 1, 2021 - Log in to answer · Best Answer · By JanBask DevOps Expert · CM · Clare Matthews · Answered on Jul 1, 2021 · Numpy one hot encoding can be done by following steps as mentioned below: rows = np.
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › how to one hot encode sequence data in python
How to One Hot Encode Sequence Data in Python - MachineLearningMastery.com
August 14, 2019 - If we receive a prediction in this 3-value one hot encoding, we can easily invert the transform back to the original label. First, we can use the argmax() NumPy function to locate the index of the column with the largest value.
🌐
GitHub
github.com › scikit-learn-contrib › category_encoders › issues › 442
Returning a numpy array in one hot encoder · Issue #442 · scikit-learn-contrib/category_encoders
September 3, 2024 - When the category_encoders.one_hot.OneHotEncoder deals with a dataframe with only numerical features, the parameter cols is empty and the parameter return_df=False, the fit_transform method returns a pd.DataFrame object. import numpy as np import pandas as pd from category_encoders.one_hot import OneHotEncoder rng = np.random.RandomState(42) n_rows = 100 col1 = rng.rand(n_rows) * 100 col2 = rng.randint(1, 100, n_rows) col3 = rng.choice([True, False], n_rows) modalities = ['A', 'B', 'C', 'D'] col4 = rng.choice(modalities, n_rows) df = pd.DataFrame({ 'Numeric1': col1, 'Numeric2': col2, 'Boolean': col3, 'Object': col4 }) encoder = OneHotEncoder( cols=df.select_dtypes(include=["object", "bool"]).columns, return_df=False, handle_missing='return_nan' ) X = encoder.fit_transform(df) type(X) Out: pandas.core.frame.DataFrame ·
Author: scikit-learn-contrib
🌐
Kaggle
kaggle.com › code › matinmahmoudi › numpy-fun-problems-expert
🌋 Numpy Fun Problems - Expert | Kaggle
May 23, 2024 - Explore and run AI code with Kaggle Notebooks | Using data from No attached data sources
🌐
IncludeHelp
includehelp.com › python › convert-array-of-indices-to-one-hot-encoded-array-in-numpy.aspx
Python - Convert array of indices to one-hot encoded array in NumPy?
May 24, 2023 - # Import numpy import numpy as np # Creating a numpy array using full method arr = np.array([1, 0, 3]) # Display original array print("Orignal array:\n",arr,"\n") # Creating a one hot encode array res = np.zeros((arr.size, arr.max() + 1)) res[np.arange(arr.size), arr] = 1 # Display result print("Result:\n",res)
🌐
GitHub
rasbt.github.io › mlxtend › user_guide › preprocessing › one-hot_encoding
One hot encoding - mlxtend
NumPy array type (float, float32, float64) of the output array. ... One-hot encoded array, where each sample is represented as a row vector in the returned array.
🌐
Clay-Technology World
clay-atlas.com › home › [python] convert the value to one-hot type in numpy
[Python] Convert the value to one-hot type in Numpy - Clay-Technology World
May 27, 2021 - Today I had a requirement for converting some data of numpy array to one-hot encoding type, so I recorded how to use eye() function built-in numpy to do it.
🌐
Intellipaat
intellipaat.com › home › blog › convert array of indices to one-hot encoded array in numpy
Convert Array of Indices to One-Hot Encoded Array in NumPy - Intellipaat
February 2, 2026 - The simplest way to convert an array of indices into a one-hot encoded format is by using NumPy’s built-in functions.