Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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, 720], [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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Thanks for any help provided !

>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] 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading