Home > Enterprise >  How to accumulate a matrix with particular position without for-loop?
How to accumulate a matrix with particular position without for-loop?

Time:05-16

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?

CodePudding user response:

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.]])
  • Related