Let's say I have 2 arrays A and B where the values in A correspond to the index in the first dimension of B
A = np.array([[ 0, 3, 4],
[ 5, 6, 0],
[ 0, 1, 9],
[11, 12, 13]])
B = np.array([[0, 1, 1],
[1, 2, 0],
[0, 2, 3],
[3, 3, 3],
[0, 3, 1],
[3, 1, 1],
[1, 1, 0]])
For each row j of B, I want to sum the elements in A that correspond to A[B[j, i], i], to get a new array of shape 7. I can do it with loops like this:
output_array = np.zeros(B.shape[0])
for i in range(A.shape[1]):
for j in range(B.shape[0]):
output_array[j] += A[B[j, i], i]
which would give me as output_array
array([ 6., 10., 14., 36., 12., 17., 15.])
Is there any fast and efficient way to do the same for large arrays without having to loop?
The closest answer I could find here was this one, but I need to actually do a sum inside one of the loop and I wasn't able to extend to my case.