Python 使用numpy数组将值分配给另一个数组
我有以下numpy数组Python 使用numpy数组将值分配给另一个数组,python,arrays,numpy,indexing,vectorization,Python,Arrays,Numpy,Indexing,Vectorization,我有以下numpy数组矩阵 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 = np.array([[1,3], [2,4], [0,4]]) array([[1, 3], [2, 4], [0, 4]]) 问题:如何将1s分配给矩阵中的
矩阵
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 = np.array([[1,3], [2,4], [0,4]])
array([[1, 3],
[2, 4],
[0, 4]])
问题:如何将1
s分配给矩阵
中的元素,这些元素的索引由索引
数组指定。预计将实现矢量化
为了更清楚,输出应该如下所示:
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
这里有一种方法是使用-
解释
我们使用np.arange(matrix.shape[0])
-
列索引已作为索引提供
-
In [19]: indices
Out[19]:
array([[1, 3],
[2, 4],
[0, 4]])
In [20]: indices.shape
Out[20]: (3, 2)
idx (row) : 3
indices (col) : 3 x 2
让我们制作一个行和列索引的形状示意图,idx
和索引
-
In [19]: indices
Out[19]:
array([[1, 3],
[2, 4],
[0, 4]])
In [20]: indices.shape
Out[20]: (3, 2)
idx (row) : 3
indices (col) : 3 x 2
为了使用行和列索引索引到输入数组矩阵
,我们需要使它们能够相互广播。一种方法是在idx
中引入一个新的轴,通过将元素推入第一个轴,并允许一个单件dim作为最后一个轴,使用idx[:,None]
,使其成为2D
,如下所示-
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
的广播元素将用作来自索引的行索引和列索引,用于索引到矩阵中,用于设置其中的元素。从那时起,我们-
idx=np.arange(matrix.shape[0])
因此,我们将以-
矩阵[np.arange(matrix.shape[0])[:,None],索引]
用于设置元素。这涉及循环,因此对于大型数组可能不是很有效
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]])
非常感谢。拯救了这一天!我用你的方法完成了我的工作,但对我来说,实现有些模糊。你能详细说明一下所执行的操作吗?@akilat90看看添加的注释是否有意义。