use*_*2pi 4 python arrays numpy multidimensional-array
你有一个形状数组(a,b,c),你想要将第二个维度乘以一个形状数组(b)
for循环可以工作,但是有更好的方法吗?
防爆.
A = np.array(shape=(a,b,c))
B = np.array(shape=(b))
for i in B.shape[0]:
A[:,i,:]=A[:,i,:]*B[i]
Run Code Online (Sandbox Code Playgroud)
使用广播:
A*B[:,np.newaxis]
Run Code Online (Sandbox Code Playgroud)
例如:
In [47]: A=np.arange(24).reshape(2,3,4)
In [48]: B=np.arange(3)
In [49]: A*B[:,np.newaxis]
Out[49]:
array([[[ 0, 0, 0, 0],
[ 4, 5, 6, 7],
[16, 18, 20, 22]],
[[ 0, 0, 0, 0],
[16, 17, 18, 19],
[40, 42, 44, 46]]])
Run Code Online (Sandbox Code Playgroud)
B[:,np.newaxis]有形状(3,1).广播在左侧添加新轴,因此广播形状(1,3,1).广播也沿着长度为1的轴重复项目.因此,当乘以时A,它进一步广播成形(2,3,4).这符合的形状A.乘法然后一如既往地以元素方式进行.