将numpy 2d数组与1d数组相乘[重复]

时间:2022-12-29 19:47:38

This question already has an answer here:

这个问题在这里已有答案:

I have a numpy 2d array:

我有一个numpy 2d数组:

[[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]]

How can I get it so that it multiplies the indices from top to bottom with the corresponding values from a 1d array when the row length of the 2d array is smaller than length of 1d array ? For example multiply above with this:

当2d数组的行长度小于1d数组的长度时,如何将索引从上到下与1d数组中的相应值相乘?例如,乘以上面这个:

[10, 20, 30, 40]

to get this:

得到这个:

 [[10, 10, 10],
 [20, 20, 20],
 [30, 30, 30]
 [40, 40, 40]]

Probably a duplicate, but I couldnt find exact thing I am looking for. Thanks in advance.

可能是重复,但我找不到我想要的确切内容。提前致谢。

1 个解决方案

#1


1  

* in numpy does element-wise multiplication, for example multiply 1d array by another 1d array:

*在numpy中进行逐元素乘法,例如将1d数组乘以另一个1d数组:

In [52]: np.array([3,4,5]) * np.array([1,2,3])
Out[52]: array([ 3,  8, 15])

When you multiply a 2d array by 1d array, same thing happens for every row of 2d array:

当你将2d数组乘以1d数组时,对于2d数组的每一行都会发生同样的事情:

In [53]: np.array([[3,4,5],[4,5,6]]) * np.array([1,2,3])
Out[53]:
array([[ 3,  8, 15],
       [ 4, 10, 18]])

For your specific example:

对于您的具体示例:

In [66]: ones = np.ones(12, dtype=np.int).reshape(4,3)

In [67]: a = np.array([10, 20, 30, 40])

In [68]: (ones.T * a).T
Out[68]:
array([[10, 10, 10],
       [20, 20, 20],
       [30, 30, 30],
       [40, 40, 40]])

#1


1  

* in numpy does element-wise multiplication, for example multiply 1d array by another 1d array:

*在numpy中进行逐元素乘法,例如将1d数组乘以另一个1d数组:

In [52]: np.array([3,4,5]) * np.array([1,2,3])
Out[52]: array([ 3,  8, 15])

When you multiply a 2d array by 1d array, same thing happens for every row of 2d array:

当你将2d数组乘以1d数组时,对于2d数组的每一行都会发生同样的事情:

In [53]: np.array([[3,4,5],[4,5,6]]) * np.array([1,2,3])
Out[53]:
array([[ 3,  8, 15],
       [ 4, 10, 18]])

For your specific example:

对于您的具体示例:

In [66]: ones = np.ones(12, dtype=np.int).reshape(4,3)

In [67]: a = np.array([10, 20, 30, 40])

In [68]: (ones.T * a).T
Out[68]:
array([[10, 10, 10],
       [20, 20, 20],
       [30, 30, 30],
       [40, 40, 40]])