mem*_*ecs 4 python arrays numpy
我试图对numpy数组的某些特定单元格求和+1,但没有慢循环我找不到任何方法:
coords = np.array([[1,2],[1,2],[1,2],[0,0]])
X = np.zeros((3,3))
for i,j in coords:
X[i,j] +=1
Run Code Online (Sandbox Code Playgroud)
导致:
X = [[ 1. 0. 0.]
[ 0. 0. 3.]
[ 0. 0. 0.]]
Run Code Online (Sandbox Code Playgroud)
X[coords[:,0],coords[:,1] += 1 退货
X = [[ 1. 0. 0.]
[ 0. 0. 1.]
[ 0. 0. 0.]]
Run Code Online (Sandbox Code Playgroud)
有什么帮助吗?
numpy.at正是针对这些情况。
In [1]: np.add.at(X,tuple(coords.T),1)
In [2]: X
Out[2]:
array([[ 1., 0., 0.],
[ 0., 0., 3.],
[ 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)