Ratio calculation in 2D numpy array

Viewed 1105

Assume the following numpy array myArray is given:

myArray = np.array([[4,0,0],
                    [1,0,1],
                    [2,1,0],
                    [0,0,2],
                    [1,3,0],
                    [1,0,1],
                    [1,0,1]])

One needs to calculate the ratio between numbers in a column to the sum of the numbers of the column. For example, the sum of column 0 is 10 so the value in column 0 and row 0 should be 0.4.

That is, the expected result of myArray above is:

[[0.4,0,0],
 [0.1,0,0.2],
 [0.2,0.25,0],
 [0,0,0.4],
 [0.1,0.75,0],
 [0.1,0,0.2],
 [0.1,0,0.2]]
1 Answers

Just do:

import numpy as np

myArray = np.array([[4,0,0],
                    [1,0,1],
                    [2,1,0],
                    [0,0,2],
                    [1,3,0],
                    [1,0,1],
                    [1,0,1]])

result = myArray / myArray.sum(axis=0)
print(result)

Output

[[0.4  0.   0.  ]
 [0.1  0.   0.2 ]
 [0.2  0.25 0.  ]
 [0.   0.   0.4 ]
 [0.1  0.75 0.  ]
 [0.1  0.   0.2 ]
 [0.1  0.   0.2 ]]
Related