1

I have a numpy array A of size 10 with values ranging from 0-4. I want to create a new 2-D array B from this with its ith column being a vector corresponding to the ith element of A.

For example, the value 1 as the first element of A would correspond to B having a column vector [0,1,0,0,0] as it's first column. A having 4 as its third element would correspond to B having it's 3rd column as [0,0,0,1,0]

I have the following code:

import numpy as np

A = np.random.randint(0,5,10)
B = np.ones((5,10))

iden = np.identity(5, dtype=np.float64)

for i in range(0,10):
    a = A[i]
    B[:,i:i+1] = iden[:,a:a+1]

print A
print B

The code is doing what it's supposed to be doing but I am sure there are more efficient ways of doing this. Can anyone please suggest some?

0

1 Answer 1

1

That could be solved by initializing an array of zeros and then integer-indexing into it with indices from A and assigning 1s, like so -

M,N = 5,10
A = np.random.randint(0,M,N)
B = np.zeros((M,N))
B[A,np.arange(len(A))] = 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Exactly what I am looking for.

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.