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

  • A+
Category:Languages

This question already has an answer here:

Is there any bulid-in function in python/numpy to conver 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]] 


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.]]) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: