cd98
cd98

Reputation: 3532

Construct two dimensional numpy array from indices and values of a one dimensional array

Say I've got

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

From this I want to obtain a matrix X with shape (len(Y), 3). In this particular case, the first row of X should have a one on the second index and zero otherwhise. The second row of X should have a one on the 0 index and zero otherwise. To be explicit:

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

How do I produce this matrix? I started with

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

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

As always, thanks for your time!

Upvotes: 7

Views: 687

Answers (3)

Jaime
Jaime

Reputation: 67427

To give a one-liner alternative to DSM's 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)

Upvotes: 3

DSM
DSM

Reputation: 353009

Maybe:

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

Upvotes: 13

Joran Beasley
Joran Beasley

Reputation: 113940

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 dont think there is an easier way (but i might be wrong)

Upvotes: 1

Related Questions