我正在尝试对 numpy 数组的某些特定单元格求和,但如果没有慢循环我找不到任何方法:
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
导致:
X = [[ 1. 0. 0.]
[ 0. 0. 3.]
[ 0. 0. 0.]]
X[coords[:,0],coords[:,1] += 1
返回
X = [[ 1. 0. 0.]
[ 0. 0. 1.]
[ 0. 0. 0.]]
有什么帮助吗?
最佳答案
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.]])
关于python - 在 Numpy 数组中累积常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863404/