将一个数组的每个元素乘以另一个数组的每个元素 [英] Multiplying every element of one array by every element of another array
问题描述
说我有两个数组,
import numpy as np
x = np.array([1, 2, 3, 4])
y = np.array([5, 6, 7, 8])
什么是最快,最Pythonic等的方式来获得一个新数组 z
,其元素数量等于 x.size * y.size
,其中元素是来自两个输入数组的每对元素(x_i,y_j)
的乘积.
What's the fastest, most Pythonic, etc., etc. way to get a new array, z
, with a number of elements equal to x.size * y.size
, in which the elements are the products of every pair of elements (x_i, y_j)
from the two input arrays.
换句话说,我正在寻找一个 z
数组,其中 z [k]
是 x [i] * y [j]
.
To rephrase, I'm looking for an array z
in which z[k]
is x[i] * y[j]
.
一种简单但效率低下的方法如下:
A simple but inefficient way to get this is as follows:
z = np.empty(x.size * y.size)
counter = 0
for i in x:
for j in y:
z[counter] = i * j
counter += 1
运行上面的代码表明,在此示例中, z
是
Running the above code shows that z
in this example is
In [3]: z
Out[3]:
array([ 5., 6., 7., 8., 10., 12., 14., 16., 15., 18., 21.,
24., 20., 24., 28., 32.])
推荐答案
在这里可以建议另外两种方法.
Two more approaches could be suggested here.
使用 矩阵乘以np.dot
:
np.dot(x[:,None],y[None]).ravel()
使用 np.einsum
:
np.einsum('i,j->ij',x,y).ravel()
运行时测试
In [31]: N = 10000
...: x = np.random.rand(N)
...: y = np.random.rand(N)
...:
In [32]: %timeit np.dot(x[:,None],y[None]).ravel()
1 loops, best of 3: 302 ms per loop
In [33]: %timeit np.einsum('i,j->ij',x,y).ravel()
1 loops, best of 3: 274 ms per loop
与 @BilalAkil的答案
相同,但具有 ravel()
>代替 flatten()
作为更快的替代方法-
Same as @BilalAkil's answer
but with ravel()
instead of flatten()
as a faster alternative -
In [34]: %timeit np.multiply.outer(x, y).ravel()
1 loops, best of 3: 211 ms per loop
In [35]: %timeit np.multiply.outer(x, y).flatten()
1 loops, best of 3: 451 ms per loop
In [36]: %timeit np.array([y * a for a in x]).flatten()
1 loops, best of 3: 766 ms per loop
这篇关于将一个数组的每个元素乘以另一个数组的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!