这里有一种使用^{}-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]用于设置元素。在