获取矩阵的上三角形及其索引的值

时间:2017-12-30 22:49:37

标签: python arrays numpy matrix

假设我们有一个距离矩阵如下:

array([[ 0.        ,  0.2039889 ,  0.25030506,  0.56118992],
       [ 0.2039889 ,  0.        ,  0.39916797,  0.6909994 ],
       [ 0.25030506,  0.39916797,  0.        ,  0.63389566],
       [ 0.56118992,  0.6909994 ,  0.63389566,  0.        ]])

如何使用索引获取上部矩阵的值:

1       0.2039889   1   2
2       0.25030506  1   3
3       0.56118992  1   4
4       0.39916797  2   3
5       0.6909994   2   4
6       0.63389566  3   4 

2 个答案:

答案 0 :(得分:1)

对于 upper 三角形,使用对角线偏移1的triu_indices来排除主对角线(基于closetCoder的建议):

a = # your array
idx = np.triu_indices(a.shape[0], 1)   # indices
stacked = np.concatenate((
                          a[idx].reshape(-1, 1),   # reshaped as column of values
                          np.array(idx).T + 1      # transposed as columns of indices
                         ), axis=1)

添加1因为显然你想要基于1的索引。

如果还需要左侧的数字1,2,3,4,......,那就是连接的另一件事:

stacked = np.concatenate((
                          np.arange(idx[0].size).reshape(-1, 1) + 1,    # numbers
                          a[idx].reshape(-1, 1), 
                          np.array(idx).T + 1
                         ), axis=1)

看起来像这样:

array([[ 1.        ,  0.2039889 ,  1.        ,  2.        ],
       [ 2.        ,  0.25030506,  1.        ,  3.        ],
       [ 3.        ,  0.56118992,  1.        ,  4.        ],
       [ 4.        ,  0.39916797,  2.        ,  3.        ],
       [ 5.        ,  0.6909994 ,  2.        ,  4.        ],
       [ 6.        ,  0.63389566,  3.        ,  4.        ]])

为了完整起见,我提到scipy.spatial.distance.squareform获取上述值,但不是索引。

答案 1 :(得分:0)

以下是使用np.triu_indices

解决问题的一种方法
# 4 - matrix shape, 1 is diagonal offset
In [67]: idxs = np.triu_indices(4, 1)

In [68]: entries = arr[idxs]

In [69]: one_based_idxs = [ ar+1 for ar in idxs]

In [70]: one_based_idxs
Out[70]: [array([1, 1, 1, 2, 2, 3]), array([2, 3, 4, 3, 4, 4])]

In [71]: entries
Out[71]: 
array([ 0.2039889 ,  0.25030506,  0.56118992,  0.39916797,  0.6909994 ,
        0.63389566])