正如标题所暗示的,我有一个数字矩阵(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’?

推荐答案

这可以通过以下矢量化方式完成:

wr = np.repeat(weights[None,:], repeats=mat.shape[0],axis=0) 
# expand weights array to match the shape of mat array
# fill the diagonal with 0
np.fill_diagonal(wght_repeat, 0)
wght_avg = np.average(mat, axis=-1, weights = wr)
print(wght_avg)
>>array([2428.5       , 2442.23079848, 2442.076961  , 2436.53850163,
   2427.76928603])

Python相关问答推荐

如何列出Python脚本中使用的所有包?

决策树分类器的基础sklearn熵和log_loss标准是否有差异?

将数组操作转化为纯numpy方法

带有计数值的Pandas数据帧

Python在通过Inbox调用时给出不同的响应

将行从一个DF添加到另一个DF

通过仅导入pandas来在for循环中进行多情节

jit JAX函数中的迭代器

Class_weight参数不影响RandomForestClassifier不平衡数据集中的结果

仅从风格中获取 colored颜色 循环

从numpy数组和参数创建收件箱

Pre—Commit MyPy无法禁用非错误消息

优化器的运行顺序影响PyTorch中的预测

如何在Polars中从列表中的所有 struct 中 Select 字段?

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

Django—cte给出:QuerySet对象没有属性with_cte''''

pandas:对多级列框架的列进行排序/重新排序

matplotlib图中的复杂箭头形状

numpy.unique如何消除重复列?