iluropoda_melanoleuca bos_taurus callithrix_jacchus canis_familiaris
ailuropoda_melanoleuca 0 84.6 97.4 44
bos_taurus 0 0 97.4 84.6
callithrix_jacchus 0 0 0 97.4
canis_familiaris 0 0 0 0
这是我所拥有的python矩阵的简短版本。我在上三角形中有信息。是否有一个简单的功能可以将上三角形复制到矩阵的下三角形?
答案 0 :(得分:31)
要在NumPy中执行此操作,不使用双循环,可以使用tril_indices
。
>>> i_lower = np.tril_indices(n, -1)
>>> matrix[i_lower] = matrix.T[i_lower] # make the matrix symmetric
请注意,您不要尝试混用tril_indices
和triu_indices
,因为它们都使用行主索引,即这不起作用:
>>> i_upper = np.triu_indices(n, 1)
>>> i_lower = np.tril_indices(n, -1)
>>> matrix[i_lower] = matrix[i_upper] # make the matrix symmetric
>>> np.allclose(dist.T, dist)
False
答案 1 :(得分:4)
如果我正确理解了这个问题,我相信这会有效
for i in range(num_rows):
for j in range(i, num_cols):
matrix[j][i] = matrix[i][j]
答案 2 :(得分:4)
最简单,最快捷(无循环)的方法如下:
import numpy as np
X= np.array([[0., 2., 3.],
[0., 0., 6.],
[0., 0., 0.]])
X = X + X.T - np.diag(np.diag(X))
print(X)
#array([[0., 2., 3.],
# [2., 0., 6.],
# [3., 6., 0.]])
答案 3 :(得分:2)
我猜这里有更好的一个:
>>> a = np.arange(16).reshape(4, 4)
>>> print(a)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> iu = np.triu_indices(4,1)
>>> il = (iu[1],iu[0])
>>> a[il]=a[iu]
>>> a
array([[ 0, 1, 2, 3],
[ 1, 5, 6, 7],
[ 2, 6, 10, 11],
[ 3, 7, 11, 15]])
答案 4 :(得分:0)
如果U是上三角矩阵,则可以使用triu并转置以使其对称:
LDU = triu(U,1)+U.T
答案 5 :(得分:0)
def inmatrix(m,n):#input Matrix Function
a=[]
for i in range(m):
b=[]
for j in range(n):
elm=int(input("Enter number in Pocket ["+str(i)+"]["+str(j)+"] "))
b.append(elm)
a.append(b)
return a
def Matrix(a):#print Matrix Function
for i in range(len(a)):
for j in range(len(a[0])):
print(a[i][j],end=" ")
print()
m=int(input("Enter number of row "))
n=int(input("Enter number of column"))
a=inmatrix(m,n) #call input Matrix function
Matrix(a)#print Matrix
t=[]#create Blank list
for i in range(m):
for j in range(n):
if i>j:#check upper triangular Elements
t.append(a[i][j])#add them in a list
k=0#variable for list
for i in range(m):
for j in range(n):
if i<j:
a[i][j]=t[k]copy list item to lower triangular
k=k+1
Matrix(a)# print Matrix after change