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
Run Code Online (Sandbox Code Playgroud)
这是我所拥有的python矩阵的简短版本.我在上三角形中有信息.是否有一个简单的功能可以将上三角形复制到矩阵的下三角形?
Ste*_*ell 41
要在NumPy中执行此操作,而不使用双循环,您可以使用tril_indices.
>>> i_lower = np.tril_indices(n, -1)
>>> matrix[i_lower] = matrix.T[i_lower] # make the matrix symmetric
Run Code Online (Sandbox Code Playgroud)
小心你不要尝试混合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
Run Code Online (Sandbox Code Playgroud)
mak*_*kis 29
与接受的答案相比,100x100 矩阵的以下速度约快 3 倍,10x10 矩阵的速度大致相同。
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.]])
Run Code Online (Sandbox Code Playgroud)
请注意,矩阵必须要么是上三角开始,要么应该按如下方式制作上三角。
rng = np.random.RandomState(123)
X = rng.randomint(10, size=(3, 3))
print(X)
#array([[2, 2, 6],
# [1, 3, 9],
# [6, 1, 0]])
X = np.triu(X)
X = X + X.T - np.diag(np.diag(X))
print(X)
#array([[2, 2, 6],
# [2, 3, 9],
# [6, 9, 0]])
Run Code Online (Sandbox Code Playgroud)
如果我正确理解了这个问题,我相信这会起作用
for i in range(num_rows):
for j in range(i, num_cols):
matrix[j][i] = matrix[i][j]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7896 次 |
| 最近记录: |