I want to improve a code where I have to sum over different indices. This is the code:
neighbors = [[1,2,4],[2,0],[1,3],[],[0]]
omega = np.random((5,5,3,3))
#Sum over indices 0 (filtered) and 2
suma = np.zeros((5,3))
for j in range(5):
for l in range(3):
suma[j,l] += np.sum(omega[neighbors[j],j,:,l])
Now I improved a little bit my code using the axis parameter of sum:
suma2 = np.zeros((5,3))
for j in range(5):
suma2[j,:] += np.sum(omega[neighbors[j],j,:,:],axis=(0,1))
I want to know how I can avoid the first loop. I tried creating an array of booleans:
neighbors_bool = np.full((5,5),False,dtype=bool)
for j in range(5):
neighbors_bool[neighbors[j],j] = True
But I don't know how to put it in the sum.