0

All arrays in the following are NumPy arrays.

I have an array of numbers, say a = [4, 5, 6]. I want to add them to an accumulation array, say s = [0, 0, 0] but I want to control which number goes to where. For instance, I want

  • s[1] += a[0],
  • s[2] += a[1], and then
  • s[2] += a[2].

So I set up an auxiliary array i = [1, 2, 2] and hope that s[i] += a would work. But it wouldn't; s[2] end up only receiving a[2], as if s[i] += a is implemented by t = [0, 0, 0]; t[i] = a; s += t.

I would like to know if there is a way to achieve my version of "s[i] += a" without having to do for-loops in pure python, as I heard that the latter is much slower.

Symbol 1
  • 123
  • 4
  • Maybe this helps https://stackoverflow.com/questions/7891247/numpy-reorder-array-by-specified-values – Bob Jan 09 '22 at 03:13
  • 2
    Look at `np.add.at`. This does an unbuffered adition tbat does what you want with duplicate indices. I can elwborate, but I think the docs are clear enough. – hpaulj Jan 09 '22 at 03:27
  • @h that's exactly what I want. Thank you. – Symbol 1 Jan 09 '22 at 03:34

0 Answers0