简体   繁体   English

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

[英]Perform operation on elements of numpy array using indexes list

I have numpy array and two python lists of indexes with positions to increase arrays elements by one. 我有numpy数组和两个python索引列表,它们的位置将数组元素增加一。 Do numpy has some methods to vectorize this operation without use of for loops? numpy是否有一些方法可以向量化此操作而不使用for循环?

My current slow implementation: 我目前执行缓慢:

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)

Output: 输出:

[[0. 0. 0. 0. 0.]
 [0. 0. 2. 1. 0.]
 [0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0.]]

np.add.at will do just that, just pass both indexes as a single 2D array/list: 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.]])
>>> 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.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM