Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to covert 1d array to Logical matrix [duplicate]

Tags:

python

numpy

Is there any bulid-in function in python/numpy to convert an array = [1, 3, 1, 2] to something like this:

array = [[0, 1, 0, 0], 
        [0, 0, 0, 1], 
        [0, 1, 0, 0], 
        [0, 0, 1, 0]]
like image 661
MarkAlanFrank Avatar asked May 20 '18 15:05

MarkAlanFrank


1 Answers

You can create an identity matrix and then use the indices to create a new re-ordered matrix:

>>> a = np.eye(4)
[Out]: array([[1., 0., 0., 0.],
              [0., 1., 0., 0.],
              [0., 0., 1., 0.],
              [0., 0., 0., 1.]])

>>> indices = [1, 3, 1, 2]
>>> a[indices]
[Out]: array([[0., 1., 0., 0.],
              [0., 0., 0., 1.],
              [0., 1., 0., 0.],
              [0., 0., 1., 0.]])
like image 133
sshashank124 Avatar answered Sep 23 '22 07:09

sshashank124