用Python中行中其他元素的总和替换矩阵的对角元素

时间:2016-10-26 14:30:33

标签: python numpy matrix diagonal

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

速率是22 x 22矩阵。

我想将Rates矩阵的对角元素替换为行中所有其他元素的总和。

例如,

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) )

我想知道我该怎么做。非常感谢。

1 个答案:

答案 0 :(得分:3)

这是NumPy数组a上的矢量化方法作为输入 -

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]])

让我们手动计算求和并与对角元素进行交叉检查 -

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