1

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)

2 Answers 2

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

This sums the columns (the example data is symetric: row and column sums are equal). A / A.sum(1, keepdims=True) avoids reshaping.
@MichaelSzczesny Nice tip if your input is symmetric (I didn't notice that)! TIL about keepdims
1

You can do this:

ideal_output = (A.T/A.sum(axis=1)).T

Hope this solved your problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.