正如标题所暗示的,我有一个数字矩阵(2d数组),它的对角线恰好与0对称. 我想使用np.Average方法,以便使用来自相同长度的矩阵行的权重数组,将其行折叠为加权平均的一维列array. 但是,由于对角线是零,因此我不想将其计入行的加权平均值的结果中. 换句话说,我希望每一行都有一组不同的权重,这样对于行i,相应的权重[i]将为零,而其余的权重将保持不变.
Is it possible to do this without an explicit loop?
What is the best way to do it?
Code example-
Generate the matrix and the weights:
mat = np.array([[ 0, 2436, 2434, 2428, 2416],
[ 2436, 0, 2454, 2446, 2435],
[ 2434, 2454, 0, 2447, 2436],
[ 2428, 2446, 2447, 0, 2428],
[ 2416, 2435, 2436, 2428, 0]])
weights = np.array([262140, 196608, 196608, 196608, 196608])
Current (wrong) implementation:
Calculate the weighted average:
weighted_avg = np.average(mat, axis=-1, weights=weights)
print(weighted_avg)
Out: [1821.38194802 1984.31077694 1984.18578409 1979.68578982 1972.56080841]
Loop implementation:个
weighted_avg = []
for i in range(mat.shape[0]):
curr_weights = weights.copy()
curr_weights[i] = 0
weighted_avg.append(np.average(mat[i], axis=-1, weights=curr_weights))
weighted_avg = np.array(weighted_avg)
print(weighted_avg)
Out: [2428.5 2442.23079848 2442.076961 2436.53850163 2427.76928603]
我怎样才能使这个循环实现使用‘合适的NumPy’?