根据另一个数组中的索引获取数组的元素

Take elements of an array based on indexes in another array

我的一侧有一组值:

A = np.arange(30).reshape((3, 10))

Out: array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
            [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
            [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])

以及引用它的索引数组,其中每一列引用 A 中的每一行。

np.random.seed(0)
index = np.random.randint(0, 9, 6).reshape((2, 3))

Out: array([[5, 0, 3],
            [3, 7, 3]])

我想获得一个与索引数组具有相同维度的数组,但将每个索引替换为其在 A 中的值。我已经能够通过以下方式完成:

 np.dstack([A[0].take(index.T[0]),        
            A[1].take(index.T[1]),        
            A[2].take(index.T[2])]).squeeze()

Out: array([[ 5, 10, 23],
            [ 3, 17, 23]])

我相信我遗漏了一些东西,这不是最好的方法。我还担心数组大小增加时的性能。是否有更通用和可扩展的方法来实现它?

您可以使用 np.take_along_axis:

np.take_along_axis(A, index.T, 1).T

array([[ 5, 10, 23],
       [ 3, 17, 23]])