3

I am trying to use advanced indexing to update arrays, but am unsure of how to do it. For example:

foo = np.array([0, 0, 0])
bar = np.array([0, 2, 1, 0])
barr = np.array([3, 6, 9, 12])
foo[bar] += barr
print(foo)

I expect:

>>> [15, 9, 6]

but instead I get

>>> [12, 9, 6]

which probably means += doesn't update the foo array. Is there another way of achieving this?

willfung
  • 61
  • 4
  • 3
    You have duplicates for index 0. Look up np.add.at – hpaulj Oct 09 '22 at 21:54
  • `np.bincount(bar, barr)` – Michael Szczesny Oct 09 '22 at 22:33
  • @hpaulj that works, thanks! Does this extend to multidimensional arrays? I tried something like foo = [[0, 0, 0], [0, 0, 0]], bar = [(1, 0), (0, 1)], but bar is not indexing as I expect from foo[bar] -> 0 0; but get [[[0 0 0] [0 0 0]], [[0 0 0] [0 0 0]]] – willfung Oct 09 '22 at 23:24
  • 1
    @hpaulj Nvm I think u also answered it in this post https://stackoverflow.com/questions/56509600/can-numpy-add-at-be-used-with-2d-indices. Thanks! – willfung Oct 10 '22 at 02:37

0 Answers0