1

I wander, is it possible to index several dimensions at once ? With some broadcasting. Example :

Suppose i have an array A, shaped (n,d). Suppose i have a indexing array, say I with integer values between 0 and d-1. Set B = A[:,I].

If shape(I) == (k,), for whaterver k, then B has shape (n,k) and B[x,y] = A[x,I[y]].

But if shape(I) == (k,p) for whatever (k,p), then i wanted B to be shaped (n,k,p) with B[x,y,z] = A[x,I[y,z]].

1° How can i get this behavior ?

2° Does it have a drawback i did not see ?

1 Answer 1

1

You can do it exactly as you described it:

import numpy as np
n = 100
d = 20
k = 10
p = 17

A = np.random.random((n, d))
I = np.random.randint(low=0, high=d, size=(k, p))
B = A[:, I]
print(B.shape)  # (n, k, p)

# Testing if the new array B is constructed as expected
x = 3
y = 5
z = 7
print(B[x, y, z])
print(A[x, I[y, z]])
print(B[x, y, z] == A[x, I[y, z]])

Its hard to answer if this is a good implementation or not, without context. But in general it is a good idea to use numpy and vectorization if you have speed in mind.

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

1 Comment

I dont know what got me confused. I think i have trouble undertanding what is the difference between masking and indexing, i'll read on that. Thanks for the reminder anyway ! You made my day..

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.