簡體   English   中英

逐行執行某個 numpy 乘法

[英]Doing a certain numpy multiplication row-wise

我有兩個 NumPy arrays 我想在每一行中相乘。 為了說明我的意思,我將代碼放在下面:

import numpy as np 

a = np.array([
     [1,2],
     [3,4],
     [5,6],
     [7,8]])


b = np.array([
     [1,2],
     [4,4],
     [5,5],
     [7,10]])

final_product=[]
for i in range(0,b.shape[0]):
    product=a[i,:]*b
    final_product.append(product)

在 NumPy 中,是否有更直接、更快和更優雅的方式來執行上述逐行乘法,而不是使用循環和列表?

通過使用適當的重塑和重復,您可以實現您想要的,這是一個簡單的實現 -

a.reshape(4,1,2) * ([b]*4)

如果長度是動態的,您可以這樣做 -

a.reshape(a.shape[0],1,a.shape[1]) * ([b]*a.shape[0])

注意:確保 a.shape[1] 和 b.shape[1] 保持相等,而 a.shape[0] 和 b.shape[0] 可以不同。

嘗試:

n = b.shape[0]
print(np.multiply(np.repeat(a, n, axis=0).reshape((a.shape[0], n, -1)), b))

印刷:

[[[ 1  4]
  [ 4  8]
  [ 5 10]
  [ 7 20]]

 [[ 3  8]
  [12 16]
  [15 20]
  [21 40]]

 [[ 5 12]
  [20 24]
  [25 30]
  [35 60]]

 [[ 7 16]
  [28 32]
  [35 40]
  [49 80]]]

此類問題可以由np.einsum處理(請參閱Doc & this post )以獲得更多理解。 這是這方面最有效的方法之一:

np.einsum("ij, kj->ikj", a, b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM