Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Python by (320 points)

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. 

1 Answer

+2 votes
by (10.9k points)
edited by

@Anisha, 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.]])

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...