2

I have an array such as this:

array =[[1,2,3],
        [5,3,4],
        [6,7,2]]

and for each member I would like to calculate the ratio of them to the sum of the row.

Therefore, the result of my question in proposed sample is:

result = [[1/(1+2+3),2/(1+2+3),3/(1+2+3)],
          [5/(5+3+4),3/(5+3+4),4/(5+3+4)],
          [6/(6+7+2),7/(6+7+2),2/(6+7+2)]]

I write the following code but it does not work because two operators have different shape:

array/array.sum(array, axis=1)
MSN
  • 173
  • 4
  • 12

1 Answers1

4

You can specify keepdim=True while doing the sum, and then you have a 2d array as result while each row stands for the row sum:

array = np.array([[1,2,3],
        [5,3,4],
        [6,7,2.]])

array/array.sum(1, keepdims=True)
#array([[ 0.16666667,  0.33333333,  0.5       ],
#       [ 0.41666667,  0.25      ,  0.33333333],
#       [ 0.4       ,  0.46666667,  0.13333333]])
Psidom
  • 209,562
  • 33
  • 339
  • 356