Search code examples
pythonarraysnumpymatrix-multiplication

Multiplying each row of an array by a list, element-wise


I have a 3 dimensionnal numpy array and a list which look like this:

array = [  [[1,2,3,10], [4,5,6,11], [7,8,9,12]],   [[1,2,3,10], [4,5,6,11], [7,8,9,12]] ]
lst = [50, 60, 70] 

I would like to multiply each column of my array by the list, element-wise. Hence, the result would look like:

result = [[[50, 100, 150, 500], [240, 300, 360, 660], [490, 560, 630, 840]], [same]]

It seems really simple to me, but I can't figure it out and I get lost in all the methods available to multiply arrays.

np.dot() does not work because : TypeError: can't multiply sequence by non-int of type 'numpy.float64' I think by comprehension might be the worst way to do it (real length on axis 0 is 1088).

I have seen this post but I basically don't understand anything.


Solution

  • You need to convert your list to array and use broadcasting:

    out = array * np.array(lst)[:,None]
    

    Output:

    array([[[ 50, 100, 150, 500],
            [240, 300, 360, 660],
            [490, 560, 630, 840]],
    
           [[ 50, 100, 150, 500],
            [240, 300, 360, 660],
            [490, 560, 630, 840]]])
    

    Used input:

    array = np.array([[[1,2,3,10], [4,5,6,11], [7,8,9,12]],
                      [[1,2,3,10], [4,5,6,11], [7,8,9,12]]])
    lst = [50, 60, 70]