将上三角复制到python矩阵中的下三角 [英] Copy upper triangle to lower triangle in a python matrix

查看:34
本文介绍了将上三角复制到python矩阵中的下三角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 iluropoda_melanoleuca bos_taurus callithrix_jacchus canis_familiarisailuropoda_melanoleuca 0 84.6 97.4 44bos_taurus 0 0 97.4 84.6callithrix_jacchus 0 0 0 97.4canis_familiaris 0 0 0 0

这是我拥有的 Python 矩阵的简短版本.我有上三角中的信息.有没有简单的函数可以将矩阵的上三角复制到下三角?

解决方案

要在 NumPy 中做到这一点,无需使用双循环,您可以使用 tril_indices.请注意,根据您的矩阵大小,这可能会比 添加转置和减去对角线 慢,尽管这种方法可能更多可读.

<预><代码>>>>i_lower = np.tril_indices(n, -1)>>>matrix[i_lower] = matrix.T[i_lower] # 使矩阵对称

注意不要尝试混合使用 tril_indicestriu_indices 因为它们都使用行主索引,即这不起作用:

<预><代码>>>>i_upper = np.triu_indices(n, 1)>>>i_lower = np.tril_indices(n, -1)>>>matrix[i_lower] = matrix[i_upper] # 使矩阵对称>>>np.allclose(matrix.T, 矩阵)错误的

       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

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. 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

这篇关于将上三角复制到python矩阵中的下三角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆