I have the following diagonal matrix
a = array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
And the desired out come is the following
array([[1, 3, 4, 5],
[3, 2, 5, 6],
[4, 5, 3, 7],
[5, 6, 7, 4]])
Each element is the sum of the corresponding diagonals. Thanks a lot
CodePudding user response:
Try:
>>> np.diag(a) np.diag(a)[:, None] - a
array([[1, 3, 4, 5],
[3, 2, 5, 6],
[4, 5, 3, 7],
[5, 6, 7, 4]])
Addendum
What if
a
is aDataFrame
?Then:
np.diag(a) np.diag(a)[:, None] - a
is also aDataFrame
(with same index and columns asa
).What if
a
is anumpy
array, but I want aDataFrame
result?Then use:
pd.DataFrame(...)
instead.
CodePudding user response:
You can use:
# get diagonal
diag = np.diag(a)
# outer sum
out = diag diag[:,None]
# or
# out = np.outer(diag, diag)
# reset diagonal
np.fill_diagonal(out, diag)
print(out)
output:
[[1 3 4 5]
[3 2 5 6]
[4 5 3 7]
[5 6 7 4]]