Apply operations over each row in array (Python)
I have an array (3 by 3) and need to output the same size array in which each value is divided by the cumulative sum over the row.
A = np.array([ [1,4,1], [4,1,9], [1,9,1]])
ideal_output = [[1/6, 4/6, 1/6], [4/14, 1/14, 9/14], [1/11, 9/11, 1/11]]
Current Code but this is outputting with wrong dimensions:
output = []
denom = 0
for i in A:
value_sum = np.cumsum(i)
denom += value_sum
for i in A:
result= i / denom
output.append(result)
Solution 1:
> A / A.sum(axis=0)[:,None]
array([[0.16666667, 0.66666667, 0.16666667],
[0.28571429, 0.07142857, 0.64285714],
[0.09090909, 0.81818182, 0.09090909]])
Solution 2:
You can do this:
ideal_output = (A.T/A.sum(axis=1)).T
Hope this solved your problem