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

问题描述 投票:0回答:2

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

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 
python arrays numpy matrix
2个回答
1
投票

对于上三角形,使用triu_indices和对角偏移1来排除主对角线(基于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,它获取上述值,但不是索引。


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])
© www.soinside.com 2019 - 2024. All rights reserved.