在 Numpy Array 中累积常数值 [英] Accumulate constant value in Numpy Array
本文介绍了在 Numpy Array 中累积常数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将 +1 与 numpy 数组的某些特定单元格相加,但我找不到没有慢循环的任何方法:
I'm trying to sum +1 to some specific cells of a numpy array but I can't find any way without slow loops:
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.]])
这篇关于在 Numpy Array 中累积常数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文