Home > Back-end >  Doing a certain numpy multiplication row-wise
Doing a certain numpy multiplication row-wise

Time:09-03

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 are more direct, faster and elegant way of doing the above row-wise multiplication in numpy?

CodePudding user response:

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.

CodePudding user response:

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]]]
  • Related