简体   繁体   English

如何将第ith行的numpy数组的各个元素与第ith行的另一个numpy数组的元素相乘?

[英]How to multiply individual elements of numpy array of row ith with element of another numpy array of row ith?

How to multiply individual elements of numpy array of row ith with element of another numpy array of row ith? 如何将第ith行的numpy数组的各个元素与第ith行的另一个numpy数组的元素相乘?

The inventory example is that I want to multiply an numpy array(containing the item's (280 of them) costing in USD, Euro) of size [280,2] with an numpy array of size [280,3] (stocks in 3 store houses(representing the column). 库存示例是我想将大小为[280,2]的numpy数组(包含以美元,欧元计价的商品(其中的280个),用大小[280,3]的numpy数组(3家商店的库存)相乘房屋(代表专栏)。

I believe I have no problem using for loops to calculate but I am trying to learn techniques of broadcasting and reshape. 我相信使用for循环进行计算没有问题,但是我正在尝试学习广播和重塑技术。 So I would like your help to point me the correct direction(or methods) 所以我希望您能帮我指出正确的方向(或方法)

Edit: Example 编辑:示例

  Array A            
  [[1.50 1.80]        
  [3    8   ]]        

  Array B
  [[5  10 20]
  [10 20 30]]

Result I require is 我需要的结果是

  [[7.5 9  11.5 18  30 36]
  30  80 60   160 90  240]]

Thanks 谢谢

The description was a bit fuzzy, as was the example: 描述有点模糊,例如:

In [264]: A=np.array([[1.5,1.8],[3,8]]); B=np.array([[5,10,20],[10,20,30]])                          
In [265]: A.shape                                                                                    
Out[265]: (2, 2)
In [266]: B.shape                                                                                    
Out[266]: (2, 3)

Looks like you are trying to do a version of outer product, which can be done with broadcasting. 看起来您正在尝试制作外部产品的版本,可以通过广播来完成。

Let's try one combination: 让我们尝试一种组合:

In [267]: A[:,:,None]*B[:,None,:]                                                                    
Out[267]: 
array([[[  7.5,  15. ,  30. ],
        [  9. ,  18. ,  36. ]],

       [[ 30. ,  60. ,  90. ],
        [ 80. , 160. , 240. ]]])

The right numbers are there, but not the right order. 正确的数字在那里,但顺序不正确。 Let's try again: 让我们再试一次:

In [268]: A[:,None,:]*B[:,:,None]                                                                    
Out[268]: 
array([[[  7.5,   9. ],
        [ 15. ,  18. ],
        [ 30. ,  36. ]],

       [[ 30. ,  80. ],
        [ 60. , 160. ],
        [ 90. , 240. ]]])

That's better - now just reshape: 更好-现在重塑:

In [269]: _.reshape(2,6)                                                                             
Out[269]: 
array([[  7.5,   9. ,  15. ,  18. ,  30. ,  36. ],
       [ 30. ,  80. ,  60. , 160. ,  90. , 240. ]])

_268 is a partial transpose of _267 , .transpose(0,2,1) . _268_267.transpose(0,2,1)的部分转置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM