使用numpy数组将值分配给另一个数组

aki*_*t90 1 python arrays indexing numpy vectorization

我有以下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]])
Run Code Online (Sandbox Code Playgroud)

假设我有这个numpy的阵列indices,以及

indices = np.array([[1,3], [2,4], [0,4]])

array([[1, 3],
       [2, 4],
       [0, 4]]) 
Run Code Online (Sandbox Code Playgroud)

问题:如何将1s 分配给数组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
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 5

这是一种使用方法NumPy's fancy-indexing-

matrix[np.arange(matrix.shape[0])[:,None],indices] = 1
Run Code Online (Sandbox Code Playgroud)

说明

我们创建行索引np.arange(matrix.shape[0])-

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

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

In [18]: idx.shape
Out[18]: (3,)
Run Code Online (Sandbox Code Playgroud)

列索引已经给出indices-

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

In [20]: indices.shape
Out[20]: (3, 2)
Run Code Online (Sandbox Code Playgroud)

让我们制作行和列索引形状的示意图,idx并且indices-

idx     (row) :      3 
indices (col) :  3 x 2
Run Code Online (Sandbox Code Playgroud)

为了使用行索引和列索引来索引到输入数组matrix,我们需要使它们相互可广播.一种方法是引入一个新的轴idx,2D通过将元素推入第一个轴并允许单个dim作为最后一个轴idx[:,None],如下所示 -

idx     (row) :  3 x 1
indices (col) :  3 x 2
Run Code Online (Sandbox Code Playgroud)

在内部,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]]) 
Run Code Online (Sandbox Code Playgroud)

因此,广播的元素idx将被用作行索引和列索引,indices用于索引到其中matrix的设置元素.从那以后,我们 -

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

因此,我们最终会 -

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