python - 对 numpy 数组的选定行求和的简洁方法

标签 python numpy

我有一个 2D numpy 数组 L,我想将其转换为另一个 numpy 数组相同的形状,使得每一行都被所有其他行的总和替换。我在下面演示了这一点。

我的问题是是否有一种更简洁/优雅的方法来执行此操作(最好使用更高级的 numpy 语法/工具)。

L = np.array([[ 0,  1,  2],
              [ 3,  4,  5],
              [ 6,  7,  8],
              [ 9, 10, 11]])

store = []
for i in range(L.shape[0]):
    store.append(np.sum(L,axis=0) - L[i])
output = np.stack(store)    

这给了我正确的输出:

array([[18, 21, 24],
       [15, 18, 21],
       [12, 15, 18],
       [ 9, 12, 15]])

最佳答案

只需从列求和中减去 L 即可利用 broadcasting也在寻求矢量化解决方案 -

In [12]: L.sum(0) - L
Out[12]: 
array([[18, 21, 24],
       [15, 18, 21],
       [12, 15, 18],
       [ 9, 12, 15]])

关于python - 对 numpy 数组的选定行求和的简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55781501/

相关文章:

python - 带键的元素最大值

python - 使用Python中的OpenCV处理图像以减少噪声

python - Google AppEngine 上的内存分析/监控 (python)

python - 使用给定的 x 和 y 值绘制直方图

python - 如何将一个数据帧分割成多个,然后将其重新拼接到一个元组中,而无需进行硬编码

python - 如何从 IDL 访问这个 'rec.array' 中的数据?

python - Peewee 示例中带有主键的 SQL 语法错误

python - Telegram Bot API : get message id to forward it

python - 元素的 numpy 条件格式

python - 将列表转换为数据框/调整一行循环