在python矩阵中将上三角复制到下三角 [英] Copy upper triangle to lower triangle in a python matrix
本文介绍了在python矩阵中将上三角复制到下三角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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矩阵的简短版本.我在上方的三角形中有此信息.是否有一个简单的函数将矩阵的上三角复制到下三角?
This is a short version of the python matrix I have. I have the information in the upper triangle. Is there an easy function to copy the upper triangle to the down triangle of the matrix?
推荐答案
To do this in NumPy, without using a double loop, you can use tril_indices
.
>>> i_lower = np.tril_indices(n, -1)
>>> matrix[i_lower] = matrix.T[i_lower] # make the matrix symmetric
请注意,不要尝试混用tril_indices
和 triu_indices
,因为它们都使用行主索引,即,这行不通:
Be careful that you do not try to mix tril_indices
and triu_indices
as they both use row major indexing, i.e., this does not work:
>>> 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
这篇关于在python矩阵中将上三角复制到下三角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文