Reputation: 287
I have (n,n) numpy array. I want to append a column vector where each element in it is the sum of the corresponding rows. I also append a row vector to the end of the matrix which is a sum of the corresponding columns. However, appending these 1D arrays is not compatible from a dimensional stand point. I want to append these, but have a matrix where the point (-1,-1) is the sum of either the last row or column (as they are equal).
Example;
x = np.random.randint(5, size=(4, 4))
columns = np.sum(x,axis=1)
rows = np.sum(np.transpose(x),axis=1)
Upvotes: 2
Views: 2859
Reputation: 19634
You can do it like that:
First let's generate some matrix a
n=5
k=4
a=np.zeros([n,k])
for i in range(n):
for j in range(k):
a[i][j]=i+2*j
Then run the following commands. This adds the row:
a=np.append(a,[np.sum(a,axis=0)],axis=0)
This calculates the column
col=np.array([np.sum(a,axis=1)])
Finally we add the column
a=np.concatenate((a,col.T),axis=1)
print(a)
Note that this takes care of the (-1,-1) entry as well.
Upvotes: 2