0

I have a numpy array of indexes e.g. [1,3,12]. I want to create another array from this such that at these indexes, I get a non-zero elements e.g. 1. So in this case, with input [1,3,12], I should get [0,1,0,1,0,0,0,0,0,0,0,0,1]. I can do it in a for loop, is there a short numpy function to achieve this?

1 Answer 1

1

With numpy you can index with lists directly:

a = [1,3,12]
vector = numpy.zeros(shape=max(a) + 1)
vector[a] = 1
Sign up to request clarification or add additional context in comments.

1 Comment

Great. Thanks. It worked after tiny change shape = max(a) + 1.

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.