1

Suppose we had two arrays: some values, e.g. array([1.2, 1.4, 1.6]), and some indices (let's say, array([0, 2, 1])) Our output is expected to be the values put into a bigger array, "addressed" by the indices, so we would get

array([[ 1.2,  0. ,  0. ],
       [ 0. ,  0. ,  1.4],
       [ 0. ,  1.6,  0. ]])

Is there a way to do this without loops, in a nice, fast way?

0

2 Answers 2

2

With

a = zeros((3,3))
b = array([0, 2, 1])
vals = array([1.2, 1.4, 1.6])

You just need to index it (with the help of arange or r_):

>>> a[r_[:len(b)], b] = vals


array([[ 1.2,  0. ,  0. ],
       [ 0. ,  0. ,  1.4],
       [ 0. ,  1.6,  0. ]])
Sign up to request clarification or add additional context in comments.

1 Comment

As an alternative: a[zip(*enumerate(b))]=vals
0

How do we modify this for higher dimensions? For example, a is a 5x4x3 array and b and vals are 5x4 arrays. then How do we modify the statement a[r_[:len(b)],b] = vals ?

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.