gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:26:16 26 4
gpt4 key购买 nike

       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 矩阵的简短版本。我在上面的三角形中有信息。有没有简单的函数可以将矩阵的上三角复制到下三角?

最佳答案

要在 NumPy 中执行此操作,无需使用双循环,您可以使用 tril_indices .请注意,根据您的矩阵大小,这可能比 adding the transpose and subtracting the diagonal 慢。虽然也许这种方法更具可读性。

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

关于python - 在python矩阵中将上三角形复制到下三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com