python - Numpy:沿特定 Axis 的外和

标签 python numpy sum axis outer-join

我正在寻找一种对二维矩阵列进行外部求和的有效方法。

假设 A 是 (2, 3) 矩阵,我想要的结果是 (3,2,2) 并定义为:

A = np.array([[a11, a12, a13],
              [a21, a22, a23]])

myWantedResult = np.array( [[[a11+a11, a11+a21],
                             [a21+a11, a21+a21]], # This is the np.add.outer(A[:,0],A[:,0])
                            [[a12+a12, a12+a22 ],
                             [a22+a12, a22+a22]], # This is the np.add.outer(A[:,1],A[:,1])
                           [[a13+a13, a13+a23],
                            [a23+a13, a23+a23]]# This is the np.add.outer(A[:,2],A[:,2])
                           ])

我已经尝试遍历该列,但它非常耗时,因为我想在大型数组上进行。 我正在寻找矢量化解决方案。

非常感谢!

最佳答案

外部添加可以通过将 A 添加到形状为 (2, 1, 3) 的 reshape 版本的 A 来完成. reshape 可以通过多种方式完成,包括 A[:, None, :]A.reshape((2, 1, 3))np. expand_dims(A, 1)。然后 A + A[:, None, :] 包含您想要的结果,但形状是 (2, 2, 3)。您可以使用 np.moveaxis 重新排列 Axis ,使形状为 (3, 2, 2)

In [174]: A                                                                                   
Out[174]: 
array([[  1,  10, 100],
       [-25,  50, 500]])

In [175]: B = np.moveaxis(A + A[:, None, :], -1, 0)                                           

In [176]: B.shape                                                                             
Out[176]: (3, 2, 2)

In [177]: B                                                                                   
Out[177]: 
array([[[   2,  -24],
        [ -24,  -50]],

       [[  20,   60],
        [  60,  100]],

       [[ 200,  600],
        [ 600, 1000]]])

关于python - Numpy:沿特定 Axis 的外和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66504767/

相关文章:

python - 使用 matplotlib 和 numpy 对图像应用复杂的变换

python - 什么是卡住的 Python 模块?

c++ - 在 C++ 中添加类?

mysql - 怎么超过1000 :00:00 time sum using mysql

database - 保持余额更新的数字总和的数据结构

python - 在 python 扩展 (.so) 中同时链接 libgfortran 和 libstdc++

python - 使用 NumPy 和 Pillow 绘制 Mandelbrot 时,程序输出明显的噪声

python - 图像中的第 4 个 channel 是什么?

Python 数学模块毕业

python - 导入多数组 numpy 扩展模块失败(仅使用 Anaconda)