将numpy数组中的每个元素乘以另一个numpy数组中的每个元素 [英] Multiply each element in numpy array by each element in another numpy array

查看:1107
本文介绍了将numpy数组中的每个元素乘以另一个numpy数组中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个数组:

a = np.array([1,2,3,4,5])
b = np.array([6,7,8])

其中,a通常是长度为m的一维数组,b通常是长度为n的一维数组,其中n!=m.我想将a和b逐元素相乘,以使最终结果的形状为(n*m, 1):

where the a is generally a 1D array of length m and b is a 1D array of length n where n!=m. I'd like to multiply a and b together elementwise such that the end result is of shape (n*m, 1):

result = np.array([6, 12, 18, 24, 30, 7, 14, 31, 28, 35, 8, 16, 24, 32, 40])

推荐答案

您可以使用b扩展为2D阵列形状后进行乘法运算. indexing.html#numpy.newaxis"rel =" nofollow> None/np.newaxis .然后,使用 .ravel 以获得所需的输出,就像这样-

You can use broadcasting for multiplication after extending b to a 2D array shape with None/np.newaxis. Then, flatten the multiplication result with .ravel for the desired output, like so -

(b[:,None]*a).ravel()

这实际上是在执行外部产品,因此也可以使用 np.outer 就像这样-

This is in effect performing outer product, so one can also use np.outer like so -

np.outer(b,a).ravel()

样品运行-

In [822]: a
Out[822]: array([1, 2, 3, 4, 5])

In [823]: b
Out[823]: array([6, 7, 8])

In [824]: (b[:,None]*a).ravel()
Out[824]: array([ 6, 12, 18, 24, 30,  7, 14, 21, 28, 35,  8, 16, 24, 32, 40])

In [825]: np.outer(b,a).ravel()
Out[825]: array([ 6, 12, 18, 24, 30,  7, 14, 21, 28, 35,  8, 16, 24, 32, 40])

这篇关于将numpy数组中的每个元素乘以另一个numpy数组中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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