Home > Back-end >  Multiplying each column by a number in a NumPy array
Multiplying each column by a number in a NumPy array

Time:04-11

I want to multiply the columns of A with the elements in X in the following order: the first element of X multiplies to the first column of A, the second element to the second column and so on.

For example, given:

import numpy as np

X=np.array([10.        ,  2.46421304,  4.99073939,  5.79902063,  0.        ]
A=np.array([[0, 1, 1, 1, 0],
       [1, 0, 1, 0, 1],
       [1, 1, 0, 1, 1],
       [1, 0, 1, 0, 1],
       [0, 1, 1, 1, 0]])

I want to produce:

array([[0, 2.464, 4.991, 5.799, 0],
       [10, 0, 4.991, 0, 0],
       [10, 2.464, 0, 5.799, 0],
       [10, 0, 4.991, 0, 0],
       [0, 2.464, 4.991, 5.799, 0]])

CodePudding user response:

You can take advantage of broadcasting in numpy to do:

result = A * X
print(result)

This gives the desired output (down to small floating point errors):

[[ 0.          2.46421304  4.99073939  5.79902063  0.        ]
 [10.          0.          4.99073939  0.          0.        ]
 [10.          2.46421304  0.          5.79902063  0.        ]
 [10.          0.          4.99073939  0.          0.        ]
 [ 0.          2.46421304  4.99073939  5.79902063  0.        ]]
  • Related