将矩阵的对角线元素替换为 Python 行中其他元素的总和
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 是一个 22 x 22 矩阵。
我想用行中所有其他元素的总和替换利率矩阵的对角线元素。
例如,
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)
我想知道我该怎么做。非常感谢。
这里是 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
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 是一个 22 x 22 矩阵。
我想用行中所有其他元素的总和替换利率矩阵的对角线元素。
例如,
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)
我想知道我该怎么做。非常感谢。
这里是 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