0

In numpy, I got stuck with an advanced case of indexing problem. Suppose that I have an array A with the shape(D0,D1,...,D(N-1),A,B). So, the first N dimensions are where I want to query for indices. The last two dimensions (A,B) are holding the actual data. I have a list of tuples of N dimensions, of length K, that act as indices into the first N dimensions, say indices. I did expect that A[indices] would return me another array of the shape (K,A,B). However this does not seems to be the case. An example:

arr = np.random.uniform(size=(4, 4, 4, 3, 3))
indices = [(0, 1, 2), (2, 1, 1), (0, 0, 1), (1, 1, 2), (2, 2, 2)]
indices = np.stack(indices, axis=0)
selected_arr = arr[indices]
print(selected_arr.shape)

The result is (5, 3, 4, 4, 3, 3) instead of (5, 3, 3). I thought that every row of the indices array would index the first three dimensions of arr, however this doesnt seem to be true.

Is there a way to achieve the indexing behavior I am thinking of in numpy?

4
  • 1
    Your indices is a (5,3) array, right? For indexing you supply a tuple, or a separate array for each dimension. arr[ indices[:,0], indices[:,1], indices[:,2] ] Commented Oct 18, 2023 at 5:07
  • 1
    With arr[indices] you are using that (5,3) array to select items along the first, size 4, dimension, hence the (5,3, ...) result. For numpy indexing, indexing with a tuple is important. Commented Oct 18, 2023 at 5:09
  • 1
    That's basically the same we just answered here: stackoverflow.com/questions/77311268/… Use arr[tuple(zip(*indices))]. No need for stack first Commented Oct 18, 2023 at 5:20
  • Thank you for the answers, I have just remembered how numpy distinguishes indexing with an ndarray and a conventional tuple, now it works! Commented Oct 18, 2023 at 8:48

0

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.