1

I have a 2D numpy array L, which I want to convert into another numpy array of the same shape such that each row is replaced by the sum of all the other rows. I have demonstrated this below.

My question is if there is a more concise/elegant way of doing this (preferably using more advanced numpy syntax/tools).

L = np.array([[ 0,  1,  2],
              [ 3,  4,  5],
              [ 6,  7,  8],
              [ 9, 10, 11]])

store = []
for i in range(L.shape[0]):
    store.append(np.sum(L,axis=0) - L[i])
output = np.stack(store)    

Which gives me the correct output:

array([[18, 21, 24],
       [15, 18, 21],
       [12, 15, 18],
       [ 9, 12, 15]])

1 Answer 1

2

Simply subtract L from the column-summations and hence leverage broadcasting too in the process for a vectorized solution -

In [12]: L.sum(0) - L
Out[12]: 
array([[18, 21, 24],
       [15, 18, 21],
       [12, 15, 18],
       [ 9, 12, 15]])
Sign up to request clarification or add additional context in comments.

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.