I have a 2 x N numpy array of indices and a 1 x N array of values. The indices range from [0, 0] to [Xmax, Ymax]. I need to populate an Xmax x Ymax array with the sum of the values at that index. The following code is a simple example.
import numpy as np
a = np.zeros((2, 2))
indices = np.array([[0, 0], [1, 1], [0, 0], [1, 1], [0, 1]])
values = np.array([1, 2, 3, 4, 5])
# The correct answer but slow
for k in range(len(values)):
a[indices[k, 0], indices[k, 1]] += values[k]
# Correct answer is [[4, 5], [0, 6]]
# One attempt but wrong
a1 = np.zeros((2, 2))
a1[indices[:,0], indices[:,1]] += values
# This produces [[3, 5], [0, 4]] which is just the last value not a running sum
The loop generates the correct answer for this but I think it is slower than it should be and not very pythonic. My attempts at a more pythonic solution are generating the wrong answer. What is the correct way to implement this?