'How to accumulate a matrix with particular position without for-loop?

sum = np.zeros((3,3))
m = np.array([[0,1,1],[1,2,0],[0,0,1]])
arr = np.array([[0],[1],[2]])
time = np.array([[10,20,30],[40,50,60],[70,80,90]])

And I want to make it like:

sum[arr,m[:,[0]]] += time[:,[0]]
sum[arr,m[:,[1]]] += time[:,[1]]
sum[arr,m[:,[2]]] += time[:,[2]]
>>> sum
array([[ 10.,  50.,   0.],
       [ 60.,  40.,  50.],
       [150.,  90.,   0.]])

How can I make it without a for-loop?



Solution 1:[1]

Here is a numpy approach:

sum = np.zeros((3,3))
vals = np.c_[np.indices(m.shape)[0].flatten(), m.flatten()].T
_, idx, inverse = np.unique( np.char.add(*vals.astype('str')),True, True)
sum[tuple(vals[:,idx])] = np.bincount(np.arange(idx.size)[inverse], time.flatten())

out[]
array([[ 10.,  50.,   0.],
       [ 60.,  40.,  50.],
       [150.,  90.,   0.]])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1