本文介绍了将2d数组乘以1d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个形状为(k,n)的2D数组a,我想将它与形状为(m,)的一维数组b'相乘':
I have an 2D-array a with shape (k,n) and I want to 'multiply' it with an 1D-array b of shape (m,):
a = np.array([[2, 8],
[4, 7],
[1, 2],
[5, 2],
[7, 4]])
b = np.array([3, 5, 5])
由于乘法",我正在寻找:
As a result of the 'multiplication' I'm looking for:
array([[[2*3,2*5,2*5],[8*3,8*5,8*5]],
[[4*3,4*5,4*5],[7*3,7*5,7*5]],
[[1*3,1*5,1*5], ..... ]],
................. ]]])
= array([[[ 6, 10, 10],
[24, 40, 40]],
[[12, 20, 20],
[21, 35, 35]],
[[ 3, 5, 5],
[ ........ ]],
....... ]]])
我当然可以通过循环来解决它,但是我正在寻找一种快速的矢量化方法.
I could solve it with a loop of course, but I'm looking for a fast vectorized way of doing it.
推荐答案
在末尾添加 np.newaxis/None
,然后与b
进行元素乘法,引入 broadcasting
,例如矢量解决方案-
Extend a
to a 3D array case by adding a new axis at the end with np.newaxis/None
and then do elementwise multiplication with b
, bringing in broadcasting
for a vectorized solution, like so -
b*a[...,None]
样品运行-
In [19]: a
Out[19]:
array([[2, 8],
[4, 7],
[1, 2],
[5, 2],
[7, 4]])
In [20]: b
Out[20]: array([3, 5, 5])
In [21]: b*a[...,None]
Out[21]:
array([[[ 6, 10, 10],
[24, 40, 40]],
[[12, 20, 20],
[21, 35, 35]],
[[ 3, 5, 5],
[ 6, 10, 10]],
[[15, 25, 25],
[ 6, 10, 10]],
[[21, 35, 35],
[12, 20, 20]]])
这篇关于将2d数组乘以1d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!