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]]
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.])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With