Search code examples
pythonarraysnumpyrowmultiplication

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?


Solution

  • 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.