7

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!

2
  • 1
    What is the question? Commented Sep 23, 2013 at 20:55
  • Fair enough: edited to explicitly ask the question Commented Sep 23, 2013 at 21:04

3 Answers 3

13

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.]])
Sign up to request clarification or add additional context in comments.

Comments

3

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)

2 Comments

I'd throw in a *1 or an .astype(int), but +1.
@DSM Your code is already very significantly faster than this without the type conversion...
1
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)

3 Comments

np.zeros((len(Y), 3)). Also may want to specify dtype=np.int as example is showing integers.
DSM comes through with a better answer :P
Thanks! In case anyone is interested, I timed @JoranBeasley's and DSM's answer with a 10000 by 3 array and the vectorising gives 744 µs per loop over 11.8 ms per loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.