numpy沿第一个轴添加 [英] numpy add along first axis

查看:268
本文介绍了numpy沿第一个轴添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过沿第一个轴简单地执行相同的加法来添加两个具有不同维度的数组.

I would like to add two arrays with different dimensions by simply performing an identical addition along the first axis.

非矢量化解决方案:

x = np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,0],[1,2]],[[3,4],[5,6],[7,8]],[[9,0],[1,2],[3,4]]]) #shape (4,3,2)
y = np.array([[1,2],[3,4],[5,6]]) #shape (3,2)

ans = np.empty(x.shape)
for i in range(x.shape[0]):
    ans[i] = x[i] + y

print(ans) #shape (4,3,2)

如何适当播放此广播?

推荐答案

由于广播[numpy-doc] ,您可以简单地使用:

Due to broadcasting [numpy-doc], you can simply use:

x + y

因此,这里我们将索引 i,j,k 处的元素计算为:

So here we calculate the element at index i,j,k as:

x ijk + y jk

xijk+yjk

这给出了:

>>> x + y
array([[[ 2,  4],
        [ 6,  8],
        [10, 12]],

       [[ 8, 10],
        [12,  4],
        [ 6,  8]],

       [[ 4,  6],
        [ 8, 10],
        [12, 14]],

       [[10,  2],
        [ 4,  6],
        [ 8, 10]]])
>>> (x + y).shape
(4, 3, 2)

如果将两个数组加在一起,例如第一个数组具有三个维,第二个数组具有两个维,而第一个左边数组的最后两个维等于右边数组的维,则右边的数组一边是广播".这意味着它被视为三维数组,其中每个子数组都等于右侧的数组.

If you add two arrays together such that the first array has for example three dimensions, and the second two dimensions, and the last two dimensions of the first left array equal the dimensions of the right array, the the array on the right side is "broacasted". It means that it is treated as a three dimensional array, where each subarray equals the array on the right side.

您可以在任意位置(例如,此答案)引入" y的额外尺寸到广播"一个特定的尺寸.

You can als "introduce" extra dimensions for y at arbitrary positions like in this answer to "broadcast" a specific dimension.

这篇关于numpy沿第一个轴添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆