Copy upper triangle to lower triangle in a python matrix

后端 未结 5 1741
耶瑟儿~
耶瑟儿~ 2020-12-24 01:31
       iluropoda_melanoleuca  bos_taurus  callithrix_jacchus  canis_familiaris
ailuropoda_melanoleuca     0        84.6                97.4                44
bos_tau         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 02:23

    To do this in NumPy, without using a double loop, you can use tril_indices. Note that depending on your matrix size, this may be slower that adding the transpose and subtracting the diagonal though perhaps this method is more readable.

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

    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(matrix.T, matrix)
    False
    

提交回复
热议问题