用3D数组进行Numpy广播 [英] numpy broadcasting with 3d arrays

查看:45
本文介绍了用3D数组进行Numpy广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以应用numpy广播(带有一维数组)

Is it possible to apply numpy broadcasting (with 1D arrays),

x=np.arange(3)[:,np.newaxis]
y=np.arange(3)
x+y=
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

类似于以下示例的3d矩阵,这样a [i]中的每个元素都像上面的示例一样被视为1D向量?

to 3d matricies similar to the one below, such that each element in a[i] is treated as a 1D vector like in the example above?

a=np.zeros((2,2,2))
a[0]=1
b=a
result=a+b

导致

result[0,0]=array([[2, 2],
                   [2, 2]])

result[0,1]=array([[1, 1],
                   [1, 1]])

result[1,0]=array([[1, 1],
                   [1, 1]])

result[1,1]=array([[0, 0],
                   [0, 0]])

推荐答案

您可以按照与它们为1d数组相同的方式执行此操作,即,在任一 a中的轴0和轴1之间插入新轴. b :

You can do this in the same way as if they are 1d array, i.e, insert a new axis between axis 0 and axis 1 in either a or b:

a + b[:,None]    # or a[:,None] + b


(a + b[:,None])[0,0]
#array([[ 2.,  2.],
#       [ 2.,  2.]])

(a + b[:,None])[0,1]
#array([[ 1.,  1.],
#       [ 1.,  1.]])

(a + b[:,None])[1,0]
#array([[ 1.,  1.],
#       [ 1.,  1.]])

(a + b[:,None])[1,1]
#array([[ 0.,  0.],
#       [ 0.,  0.]])

这篇关于用3D数组进行Numpy广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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