如何在没有for循环的情况下累加具有特定位置的矩阵?
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]])
我想把它变成这样:
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.]])
没有 for-loop 怎么实现?
这是一个 numpy 方法:
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.]])
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]])
我想把它变成这样:
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.]])
没有 for-loop 怎么实现?
这是一个 numpy 方法:
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.]])