Build a two-dimensional numpy array from indices and values โ€‹โ€‹of a one-dimensional array

Let's say i have

Y = np.array([2, 0, 1, 1]) 

From here I want to get a matrix X with the form (len(Y), 3) . In this particular case, the first row of X should have one at the second index and zero at the other. The second line of X must have one index 0 and zero otherwise. To be explicit:

 X = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 0]]) 

How can I create this matrix? I started with

 X = np.zeros((Y.shape[0], 3)) 

but then couldn't figure out how to populate / populate those from the list of indices

As always, thanks for your time!

+7
python numpy
source share
3 answers

May be:

 >>> Y = np.array([2, 0, 1, 1]) >>> X = np.zeros((len(Y), 3)) >>> X[np.arange(len(Y)), Y] = 1 >>> X array([[ 0., 0., 1.], [ 1., 0., 0.], [ 0., 1., 0.], [ 0., 1., 0.]]) 
+13
source share

To give a one-line alternative to DSM, a perfectly good answer:

 >>> Y = np.array([2, 0, 1, 1]) >>> np.arange(3) == Y[:, np.newaxis] array([[False, False, True], [ True, False, False], [False, True, False], [False, True, False]], dtype=bool) 
+3
source share
 Y = np.array([2, 0, 1, 1]) new_array = np.zeros((len(Y),3)) for i in range(len(Y)): new_array[i,Y[i]] = 1 

I think ... I don't think there is an easier way (but I could be wrong)

+1
source share

All Articles