numpy - How can I calculate the ratio of a value in array to the sum of array in python? -


this question has answer here:

i have array such this:

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

and each member calculate ratio of them sum of row.

therefore, result of 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 following code not work because 2 operators have different shape:

array/array.sum(array, axis=1) 

you can specify keepdim=true while doing sum, , have 2d array result while each row stands 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]]) 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -