在python矩阵中将上三角复制到下三角

发布于 2021-01-29 15:06:56

       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
被浏览
101
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    要在NumPy中执行此操作,而无需使用双循环,可以使用tril_indices。请注意,根据矩阵的大小,这可能会比添加转置和减去对角线慢一些,尽管此方法可能更具可读性。

    >>> i_lower = np.tril_indices(n, -1)
    >>> matrix[i_lower] = matrix.T[i_lower]  # make the matrix symmetric
    

    注意不要混用tril_indicestriu_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(matrix.T, matrix)
    False
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看