0

Suppose that I have a numpy array of integers like this: [0,1,2,0,0,1,3]. How can I make it into a binary array whose non-zeros entries are defined by [0,1,2,0,0,1,3], i.e.:

array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 0., 1.]])

I'm currently using the following code to do it:

dummy_indices = np.array([0,1,2,0,0,1,3])
dummy_array = np.zeros([dummy_indices.shape[0],(1+np.max(dummy_indices))])
for i in range(dummy_array.shape[0]):
    dummy_array[i,dummy_indices[i]] =1

Is there a faster loop-free way to go about it?

0

1 Answer 1

1

You could do something like this:

x = np.array([0,1,2,0,0,1,3]) #your init array
y = np.zeros(shape=(x.shape[0], x.max()+1))
y[np.arange(x.shape[0]), x] = 1

y
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 0., 1.]])

Sign up to request clarification or add additional context in comments.

Comments

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.