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

时间:2020-01-13 16:14:46

标签: python arrays numpy indexing take

我的一侧有一个值数组:

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]])

我相信我缺少某些东西,但这并不是最佳选择。当数组的大小增加时,我也担心性能。有没有更通用且可扩展的方法来实现这一目标?

1 个答案:

答案 0 :(得分:3)

您可以使用np.take_along_axis

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

array([[ 5, 10, 23],
       [ 3, 17, 23]])
相关问题