4

我正在尝试P用另一个数组索引一个多维数组indices。它指定了我想要的最后一个轴上的哪个元素,如下所示:

import numpy as np

M, N = 20, 10

P = np.random.rand(M,N,2,9)

# index into the last dimension of P
indices = np.random.randint(0,9,size=(M,N))

# I'm after an array of shape (20,10,2)
# but this has shape (20, 10, 2, 20, 10)
P[...,indices].shape 

如何正确索引Pindices获取形状数组(20,10,2)

如果这不是太清楚:对于任何ij(在界限内)我想my_output[i,j,:]等于P[i,j,:,indices[i,j]]

4

1 回答 1

2

我认为这会起作用:

P[np.arange(M)[:, None, None], np.arange(N)[:, None], np.arange(2),
  indices[..., None]]

不漂亮,我知道...


这可能看起来更好,但也可能不太清晰:

P[np.ogrid[0:M, 0:N, 0:2]+[indices[..., None]]]

或者更好:

idx_tuple = tuple(np.ogrid[:M, :N, :2]) + (indices[..., None],)
P[idx_tuple]
于 2013-03-27T14:19:39.167 回答