numpy中两个数组的乘法

Multiplication of two arrays in numpy

我有两个 numpy 数组:

x = numpy.array([1, 2])
y = numpy.array([3, 4])

我想创建一个元素矩阵:

[[3, 6],
 [4, 8]]

最简单的方法是什么?

你可以使用 np.outer.

In [7]: x = np.array([1, 2])

In [8]: y = np.array([3, 4])

In [10]: np.outer(x,y).T
Out[10]: 
array([[3, 6],
       [4, 8]])

一种方法是使用 np.multiplyouter 函数(如果您想要与问题中的顺序相同,则转置):

>>> np.multiply.outer(x, y).T
array([[3, 6],
       [4, 8]])

NumPy 中的大多数 ufunc 都有这个有用的 outer 特性(addsubtractdivide 等)。由于 np.outer 等价于此处的乘法情况。

或者,np.einsum可以一次性执行乘法和转置:

>>> np.einsum('i,j->ji', x, y)
array([[3, 6],
       [4, 8]])

第三种方法是在一个数组中插入一个新轴然后相乘,尽管这有点冗长:

>>> (x[:, np.newaxis] * y).T
array([[3, 6],
       [4, 8]])

对于那些对性能感兴趣的人,这里是两个长度为 15 的数组的操作时间,从最快到最慢:

In [70]: x = np.arange(15)
In [71]: y = np.arange(0, 30, 2)
In [72]: %timeit np.einsum('i,j->ji', x, y)
100000 loops, best of 3: 2.88 µs per loop
In [73]: %timeit np.multiply.outer(x, y).T
100000 loops, best of 3: 5.48 µs per loop
In [74]: %timeit (x[:, np.newaxis] * y).T
100000 loops, best of 3: 6.68 µs per loop
In [75]: %timeit np.outer(x, y).T
100000 loops, best of 3: 12.2 µs per loop

B = np.multiply.outer(x, y).T

link: http://pchanial.github.io/python-for-data-scientists/auto_examples/ufunc_matrices.html

这里有一个很好的教程来解决这些问题 这个地址可以提供帮助:http://wiki.scipy.org/Tentative_NumPy_Tutorial