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?
indicesis 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] ]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.arr[tuple(zip(*indices))]. No need forstackfirst