遍历 Python 中矩阵的上三角

Traversing the upper triangle of a matrix in Python

假设存在一个矩阵 M(可以使用 numpy 数组或 DataFrames 存储)并且想要获取 M 上三角中除主矩阵之外的所有条目的元组列表 (r,c,v)对角线,这样 r 是行索引,c 是列索引,v 是由 r 和 c 索引的 M 中的值。

阅读到目前为止我学到的不同问题,我可以使用 np.triu_indices 或类似的函数构建一个三角索引器,但这让我失去了哪些索引对应于给定值的信息。例如,在 Get indices of matrix from upper triangle 中讨论了矩阵的最大值,但我很难将其概括为获得上面定义的所有值的列表。

方阵上三角不包括主对角线的值都是列索引大于行索引的值:

import numpy as np

M = np.array([[10, 11, 12, 13],
              [14, 15, 16, 17],
              [18, 19, 20, 21],
              [22, 23, 24, 15]])

for r in range(M.shape[0]):
    for c in range(r + 1, M.shape[0]):
        v = M[r, c]
        print(r, c, v)