Value accumulation at the bottom right of a matrix

import numpy as np A = np.array([ [4,5,12,7], [6,4,9,0], [3,6,8,14], [6,8,12,7], [9,15,8,4] ]) hor_sum = np.sum(A, axis = 1) ver_sum = np.sum(A, axis = 0) total_sum = np.sum(hor_sum) + np.sum(ver_sum) # First variant: Copy to a larger matrix rows, cols = A.shape A_extended = np.zeros((rows+1, cols+1), dtype=np.int) A_extended[:rows, :cols] = A[:,:] A_extended[:rows, -1] = hor_sum A_extended[-1, :cols] = ver_sum A_extended[-1, -1] = total_sum # Second variant: In-place A = np.column_stack((A, hor_sum)) A = np.row_stack((A, np.hstack((ver_sum, total_sum)))) assert np.all(A_extended == A) print(A) """ [[ 4 5 12 7 28] [ 6 4 9 0 19] [ 3 6 8 14 31] [ 6 8 12 7 33] [ 9 15 8 4 36] [ 28 38 49 32 294]] """