Reputation: 2217
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]])
Upvotes: 1
Views: 976
Reputation: 221574
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]])
Upvotes: 2