如何将numpy数组乘以列表以获得多维数组?

时间:2023-01-28 12:32:13

In Python, I have a list and a numpy array.

在Python中,我有一个列表和一个numpy数组。

I would like to multiply the array by the list in such a way that I get an array where the 3rd dimension represents the input array multiplied by each element of the list. Therefore:

我希望将数组乘以列表,使得我得到一个数组,其中第三维表示输入数组乘以列表的每个元素。因此:

in_list = [2,4,6]
in_array = np.random.rand(5,5)
result = ...
np.shape(result) ---> (3,5,5) 

where (0,:,:) is the input array multiplied by the first element of the list (2); (1,:,:) is the input array multiplied by the second element of the list (4), etc.

其中(0,:,:)是输入数组乘以列表的第一个元素(2); (1,:,:)是输入数组乘以list(4)的第二个元素等。

I have a feeling this question will be answered by broadcasting, but I'm not sure how to go around doing this.

我有一种感觉,这个问题将通过广播来回答,但我不知道如何绕过这样做。

1 个解决方案

#1


3  

You want np.multiply.outer. The outer method is defined for any NumPy "ufunc", including multiplication. Here's a demonstration:

你想要np.multiply.outer。外部方法是为任何NumPy“ufunc”定义的,包括乘法。这是一个演示:

In [1]: import numpy as np

In [2]: in_list = [2, 4, 6]

In [3]: in_array = np.random.rand(5, 5)

In [4]: result = np.multiply.outer(in_list, in_array)

In [5]: result.shape
Out[5]: (3, 5, 5)

In [6]: (result[1, :, :] == in_list[1] * in_array).all()
Out[6]: True

As you suggest, broadcasting gives an alternative solution: if you convert in_list to a 1d NumPy array of length 3, you can then reshape to an array of shape (3, 1, 1), and then a multiplication with in_array will broadcast appropriately:

正如您所建议的那样,广播提供了另一种解决方案:如果将in_list转换为长度为3的1d NumPy数组,则可以重塑为形状数组(3,1,1),然后使用in_array进行相乘广播:

In [9]: result2 = np.array(in_list)[:, None, None] * in_array

In [10]: result2.shape
Out[10]: (3, 5, 5)

In [11]: (result2[1, :, :] == in_list[1] * in_array).all()
Out[11]: True

#1


3  

You want np.multiply.outer. The outer method is defined for any NumPy "ufunc", including multiplication. Here's a demonstration:

你想要np.multiply.outer。外部方法是为任何NumPy“ufunc”定义的,包括乘法。这是一个演示:

In [1]: import numpy as np

In [2]: in_list = [2, 4, 6]

In [3]: in_array = np.random.rand(5, 5)

In [4]: result = np.multiply.outer(in_list, in_array)

In [5]: result.shape
Out[5]: (3, 5, 5)

In [6]: (result[1, :, :] == in_list[1] * in_array).all()
Out[6]: True

As you suggest, broadcasting gives an alternative solution: if you convert in_list to a 1d NumPy array of length 3, you can then reshape to an array of shape (3, 1, 1), and then a multiplication with in_array will broadcast appropriately:

正如您所建议的那样,广播提供了另一种解决方案:如果将in_list转换为长度为3的1d NumPy数组,则可以重塑为形状数组(3,1,1),然后使用in_array进行相乘广播:

In [9]: result2 = np.array(in_list)[:, None, None] * in_array

In [10]: result2.shape
Out[10]: (3, 5, 5)

In [11]: (result2[1, :, :] == in_list[1] * in_array).all()
Out[11]: True