使用索引列表对numpy数组的元素执行操作

Bha*_*rag 0 python numpy

我有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)
Run Code Online (Sandbox Code Playgroud)

输出:

[[0. 0. 0. 0. 0.]
 [0. 0. 2. 1. 0.]
 [0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0.]]
Run Code Online (Sandbox Code Playgroud)

Tom*_*ias 6

np.add.at 只会这样做,只需将两个索引作为单个2D数组/列表传递:

a = np.zeros([4,5])
xs = [1, 1, 1, 3]
ys = [2, 2, 3, 0]

np.add.at(a, [xs, ys], 1) # in-place
print(a)

array([[0., 0., 0., 0., 0.],
       [0., 0., 2., 1., 0.],
       [0., 0., 0., 0., 0.],
       [1., 0., 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)