0

I have numpy array and two python lists of indexes with positions to increase arrays elements by one. Do numpy has some methods to vectorize this operation without use of for loops?

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.]]
2
  • 2
    As you treat some indices different than others, this won't be the result of one vectorized operation. You increment one index twice, the others only once. Commented Jun 30, 2018 at 14:36
  • @SpghttCd Exactly, I want to perform this operation as many times as much occurences are present in index list. Commented Jun 30, 2018 at 14:38

2 Answers 2

5

np.add.at will do just that, just pass both indexes as a single 2D array/list:

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.]])
Sign up to request clarification or add additional context in comments.

Comments

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.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.