我有numpy数组和两个python索引列表,它们的位置使数组元素增加一。 numpy是否有一些方法可以向量化此操作而不使用for
循环?
我目前的执行缓慢:
a = np.zeros([4,5])
xs = [1,1,1,3]
ys = [2,2,3,0]
for x,y in zip(xs,ys): # how to do it in numpy way (efficiently)?
a[x,y] += 1
print(a)
输出:
[[0. 0. 0. 0. 0.]
[0. 0. 2. 1. 0.]
[0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0.]]
答案 0 :(得分:6)
pc.onnegotiationneeded = e => {
if (pc.signalingState != "stable") return;
..
}
可以做到这一点,只需将两个索引作为单个2D数组/列表传递即可:
np.add.at
答案 1 :(得分:1)
>>> a = np.zeros([4,5])
>>> xs = [1, 1, 1, 3]
>>> ys = [2, 2, 3, 0]
>>> a[[xs,ys]] += 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 0.],
[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.]])