使用numpy数组为另一个数组赋值

2024-04-19 23:38:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下numpy数组matrix

matrix = np.zeros((3,5), dtype = int)

array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

假设我也有这个numpy数组indices

^{pr2}$

问题:如何将1分配给matrix中的元素,它们的索引由indices数组指定。需要矢量化实现。在

为了更清晰,输出应该如下所示:

    array([[0, 1, 0, 1, 0], #[1,3] elements are changed
           [0, 0, 1, 0, 1], #[2,4] elements are changed
           [1, 0, 0, 0, 1]]) #[0,4] elements are changed

Tags: numpy元素npzeros数组elementsarray矢量化
2条回答

这里有一种使用^{}-

matrix[np.arange(matrix.shape[0])[:,None],indices] = 1

说明

我们使用np.arange(matrix.shape[0])-

^{pr2}$

列索引已指定为indices-

In [19]: indices
Out[19]: 
array([[1, 3],
       [2, 4],
       [0, 4]])

In [20]: indices.shape
Out[20]: (3, 2)

让我们制作一个行和列索引的形状的示意图,idx和{}-

idx     (row) :      3 
indices (col) :  3 x 2

为了使用行和列索引索引到输入数组matrix,我们需要使它们相互广播。一种方法是在idx中引入一个新的轴,通过将元素推入第一个轴,并允许使用idx[:,None]作为最后一个轴,从而使其成为{},如下所示-

idx     (row) :  3 x 1
indices (col) :  3 x 2

在内部,idx将被广播,如下-

In [22]: idx[:,None]
Out[22]: 
array([[0],
       [1],
       [2]])

In [23]: indices
Out[23]: 
array([[1, 3],
       [2, 4],
       [0, 4]])

In [24]: np.repeat(idx[:,None],2,axis=1) # indices has length of 2 along cols
Out[24]: 
array([[0, 0],  # Internally broadcasting would be like this
       [1, 1],
       [2, 2]]) 

因此,来自idx的广播元素将用作来自indices的行索引和列索引,用于索引到{}中以设置其中的元素。因为,我们-

idx = np.arange(matrix.shape[0])

因此,我们将以-

matrix[np.arange(matrix.shape[0])[:,None],indices]用于设置元素。在

这涉及到循环,因此对于大型阵列可能不是很有效

for i in range(len(indices)):
    matrix[i,indices[i]] = 1

> matrix
 Out[73]: 
array([[0, 1, 0, 1, 0],
      [0, 0, 1, 0, 1],
      [1, 0, 0, 0, 1]])

相关问题 更多 >