Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy tuple-index based 2d array additive assignment

Tags:

python

numpy

If we have a 2d array, for example 100x100, and we want to add values to it based on their coordinates, how can we avoid overwriting the previous coordinate value's value?

import numpy as np

vm_map = np.zeros((100,100))
a = np.array([[0,1], [10,10], [40,40], [40,40]])
vm_map[tuple(a.T)] = vm_map[tuple(a.T)] + [1,.5,.3, .2]

print(vm_map[40,40])

We would like this code block to print .5, adding the two [40,40] coordinates, instead it prints .2, as that was the last value it received at that coordinate.

like image 518
Fosa Avatar asked Apr 07 '26 01:04

Fosa


1 Answers

You could use np.add.at for an in-place addition at the specified coordinates:

vm_map = np.zeros((100,100))
a = np.array([[0,1], [10,10], [40,40], [40,40]])

np.add.at(vm_map, tuple(zip(*a)), [1,.5,.3, .2])

print(vm_map)
array([[0., 1., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       ...,
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.]])
like image 181
yatu Avatar answered Apr 09 '26 14:04

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!