简体   繁体   中英

Replace the diagonal elements of a matrix with sum of other elements in the row in Python

import pandas as pd
import numpy as np
rates=(pd.read_excel("C:\Anaconda3\RateMatrix.xlsx", sheetname="Pu239Test", skiprows=0)).as_matrix() #read the matrix values from excel spreadsheet, and converts the values to a matrix

rates is a 22 x 22 matrix.

I would like to replace the diagonal elements of the Rates matrix with the sum of all other elements in the row.

For example,

rates.item(0,0) = rates.item(0,1)+rates.item(0,2)+rates.item(0,3)+....rates.item(0,21)

rates.item(1,1) = rates.item(1,0)+rates.item(1,2)+rates.item(1,3)+....rates.item(1,21)

.....

rates.item(21,21) = rates.item(21,0)+rates.item(21,2)+rates.item(21,3)+....rates.item(21,20)

I was wondering how I can do that. Thanks a lot in advance.

Here's a vectorized approach on a NumPy array a as input -

In [171]: a        # Input array
Out[171]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

# Get row and column indices of diag elements    
In [172]: row,col = np.diag_indices_from(a)

# Assign the sum of each row except the diag elems into diag positions
In [173]: a[row,col] = a.sum(axis=1) - a[row,col]

# Updated array
In [174]: a
Out[174]: 
array([[10,  1,  2,  3,  4],
       [ 5, 29,  7,  8,  9],
       [10, 11, 48, 13, 14],
       [15, 16, 17, 67, 19],
       [20, 21, 22, 23, 86]])

Let's manually compute the summations and cross-check against the diagonal elements -

In [175]: a[0,1] + a[0,2] + a[0,3] + a[0,4]
Out[175]: 10

In [176]: a[1,0] + a[1,2] + a[1,3] + a[1,4]
Out[176]: 29

In [177]: a[2,0] + a[2,1] + a[2,3] + a[2,4]
Out[177]: 48

In [178]: a[3,0] + a[3,1] + a[3,2] + a[3,4]
Out[178]: 67

In [179]: a[4,0] + a[4,1] + a[4,2] + a[4,3]
Out[179]: 86

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM