akh
akh

Reputation: 13

How to change a numpy array in to a specific matrix with 0 and 1

Suppose we have an numpy array like;

a=[1,1,2,3]

how we can change 'a' into a 4*4 matrix like:

[0 1 o o
0 1 0 0
0 0 1 0
0 0 0 1]

I mean, by calling each element, it give us a vector with the value of 1 in the corresponding index. Thank you

Upvotes: 0

Views: 33

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

I am not sure if numpy has any predefined functions to do this, but a simple way to do this via for loop would be -

In [61]: a
Out[61]: array([1, 1, 2, 3])

In [83]: i = np.zeros((a.shape[0],a.max()+1))

In [84]: for x,y in enumerate(a):
   ....:     i[x,y] = 1
   ....:

In [85]: i
Out[85]:
array([[ 0.,  1.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]])

Upvotes: 1

Related Questions