Numpy:Select 沿轴索引数组

Numpy: Select by index array along an axis

我想 select 数组中的元素沿着给定索引数组的特定轴。例如,给定数组

a = np.arange(30).reshape(5,2,3)
idx = np.array([0,1,1,0,0])

我想根据idxa的第二个维度select,这样得到的数组的形状是(5,3)。有人可以帮我吗?

我认为这会给出您想要的结果 - 它使用 np.take_along_axis,但首先您需要重塑 idx 数组,使其也是一个 3d 数组:

a = np.arange(30).reshape(5, 2, 3)
idx = np.array([0, 1, 1, 0, 0]).reshape(5, 1, 1)
results = np.take_along_axis(a, idx, 1).reshape(5, 3)

给予:

[[ 0  1  2]
 [ 9 10 11]
 [15 16 17]
 [18 19 20]
 [24 25 26]]

你可以使用花哨的索引

a[np.arange(5),idx]

输出:

array([[ 0,  1,  2],
       [ 9, 10, 11],
       [15, 16, 17],
       [18, 19, 20],
       [24, 25, 26]])

为了更详细,这与:

x,y,z = np.arange(a.shape[0]), idx, slice(None)
a[x,y,z]

xy 正在广播到形状 (5,5)z 可用于 select 输出中的任何列。