3

Assume there is a 4 dimension array idx1, stores 5 th dimension index for another 5 dimension array zeros1. like:

N,T,H,W = idx1.shape
zeros1 = np.zeros( (N,T,H,W, 256) )
# it is guaranteed that idx1's value <256

I want to realize

for n in range(N):
    for t in range(T):
        for h in range(H):
            for w in range(W):
                x = idx1[ n,t,h,w ]
                zeros1[n,t,h,w,x] = 1

How can I do it with numpy advanced indexing.

1 Answer 1

2

Use open-range arrays and index to assign -

out = np.zeros( (N,T,H,W, 256) )
i,j,k,l = np.ogrid[:N,:T,:H,:W]
out[i,j,k,l,idx1] = 1

Alternatively, in one-line -

out[tuple((np.ogrid[:N,:T,:H,:W]+[idx1]))] = 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.