简体   繁体   中英

Doing a certain numpy multiplication row-wise

I have two NumPy arrays that I would like to multiply with each other across every row. To illustrate what I mean I have put the code below:

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)

Rather than using loops and lists, is there more direct, faster and elegant way of doing the above row-wise multiplication in NumPy?

By using proper reshaping and repetition you can achieve what you are looking for, here is a simple implementation -

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

If the length is dynamic you can do this -

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

Note: Make sure a.shape[1] and b.shape[1] remains equal, while a.shape[0] and b.shape[0] can differ.

Try:

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

Prints:

[[[ 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]]]

This type of problems can be handled by np.einsum (see Doc & this post ) for more understanding. It is one of the most efficient ways in this regard:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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