Home > Net >  Python - Divide each row by a vector
Python - Divide each row by a vector

Time:12-15

I have a 10x10 matrix and I want to divide each row of the matrix with the elements of a vector.

For eg: Suppose I have a 3x3 matrix

1 1 1
2 2 2
3 3 3

and a vector [1, 2, 3]

Then this is the operation I wish to do:

1/1 1/2 1/3
2/1 2/1 2/3
3/1 3/2 3/3

i.e, divide the elements of a row by the elements of a vector(A python list)

I can do this using for loops. But, is there a better way to do this operation in python?

CodePudding user response:

You should look into broadcasting in numpy. For your example this is the solution:

a = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
b = np.array([1, 2, 3]).reshape(1, 3)
c = a / b 
print(c)
>>> [[1.         0.5        0.33333333]
     [2.         1.         0.66666667]
     [3.         1.5        1.        ]]

CodePudding user response:

The first source array should be created as a Numpy array:

a = np.array([
    [ 1, 1, 1 ],
    [ 2, 2, 2 ],
    [ 3, 3, 3 ]])

You don't need to reshape the divisor array (it can be a 1-D array, as in your source data sample):

v = np.array([1, 2, 3])

Just divide them:

result = a / v

and the result is:

array([[1.        , 0.5       , 0.33333333],
       [2.        , 1.        , 0.66666667],
       [3.        , 1.5       , 1.        ]])
  • Related