3

I have 2 arrays:
- image is a NxN array,
- indices is a Mx2 array, where the last dimension stores valid indices into image.

I want to add 1 in image for each occurrence of that index in indices.

It seems like numpy.add.at(image, indices, 1) should do the trick, except that I can't get it to perform 2-d indexing into the image:

image = np.zeros((5,5), dtype=np.int32)
indices = np.array([[1,1], [1,1], [3,3]])
np.add.at(image, indices, 1)
print(image)

Result:

[[0 0 0 0 0]
 [4 4 4 4 4]
 [0 0 0 0 0]
 [2 2 2 2 2]
 [0 0 0 0 0]]

Desired result:

[[0 0 0 0 0]
 [0 2 0 0 0]
 [0 0 0 0 0]
 [0 0 0 1 0]
 [0 0 0 0 0]]
user1411900
  • 384
  • 4
  • 14
  • What's the error? – hpaulj Jun 08 '19 at 19:43
  • From the docs: `If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects.` `indices` isn't a tuple, is it? – hpaulj Jun 08 '19 at 19:47
  • You must 1) transpose `indices` and 2) convert the result to tuple as @hpaulj points out. – Paul Panzer Jun 08 '19 at 19:57
  • Yeah I read the docs, but I guess I don't understand what they mean. Transposing indices doesn't seem to help. Can you give me a code example? Thanks! – user1411900 Jun 08 '19 at 21:45

1 Answers1

10
In [477]: np.add.at(x,(idx[:,0],idx[:,1]), 1)                                                          
In [478]: x                                                                                            
Out[478]: 
array([[0., 0., 0., 0., 0.],
       [0., 2., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 0.]])

or equivalently

In [489]: np.add.at(x,tuple(idx.T), 1)                                                                 
In [490]: x                                                                                            
Out[490]: 
array([[0., 0., 0., 0., 0.],
       [0., 2., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 0.]])

where:

In [491]: tuple(idx.T)                                                                                 
Out[491]: (array([1, 1, 3]), array([1, 1, 3]))
In [492]: x[tuple(idx.T)]                                                                              
Out[492]: array([2., 2., 1.])
hpaulj
  • 221,503
  • 14
  • 230
  • 353