About this question
I want to encode a 1-D numpy array:
x = array([1,0,3]) As a 2-D 1-hot array
y = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])Suggest me some faster technique other than looping.
I want to encode a 1-D numpy array:
x = array([1,0,3]) As a 2-D 1-hot array
y = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])Suggest me some faster technique other than looping.
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask DevOps Expert
Answered on Jul 1, 2021
Numpy one hot encoding can be done by following steps as mentioned below:
rows = np. arange(data. size)
print(rows)
one_hot[rows, data] = 1.
print(one_hot)OR
You can also refer to the following code it may help.
>>> x = [1, 0, 3]
>>> z = np.max(x) + 1
>>> np.eye(z)[x]
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])Alernatively, you can use:
>>> x = np.array([1, 0, 3])
>>> z= np.zeros((3, 4))
>>> z[np.arange(3), x] = 1
>>> y
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common DevOps interview questions, answered
Guides, tips and career advice on DevOps from JanBask experts.
DevOps How to Become a DevOps Engineers: Learning Path, Critical skills & More
Looking for answer to how to become a DevOps engineer in 2025? Here is the detailed article about DevOps career path, DevOps…
DevOps Top 50+ Jenkins Interview Questions And Answers For 2025
Here are the Top 50 Jenkins interview questions frequently asked in top MNCs which will help you land an ideal job! These…
DevOps Best 37 DevOps Tools To Learn And Master In 2025: Docker, Git & More
Want to know what are Devops tools and their uses? Or looking for the best DevOps list for automation, monitoring, & development?…
DevOps DevOps Engineer Job Description: Roles and Responsibilities [2025 Updated]
Discover the essential roles and responsibilities of a DevOps Engineer by exploring the detailed DevOps job description, and…