【问题标题】:How to get triangle upper matrix without the diagonal using numpy如何使用numpy获得没有对角线的三角形上矩阵
【发布时间】:2018-04-29 02:40:53
【问题描述】:

假设我有以下矩阵:

A = np.array([
     [1,2,3],
     [4,5,6],
     [7,8,9]])

如何有效地提取没有对角线的上三角矩阵? 输出将是以下数组:

B = np.array([2,3,6])

【问题讨论】:

  • 你试过numpy.triu吗?
  • 这里的并不是真正的矩阵,而是包含列表的元组。
  • @en_lorithai 大概他们只是想给出他们的矩阵的表示并且知道这一点。
  • @miradulo 的印象是代码应该是可验证的,但没关系。

标签: python numpy matrix


【解决方案1】:
np.triu(A, k=1)
indices = np.where(np.triu(np.ones(A.shape), k=1).astype(bool))
print(A[x])
[2 3 6]

【讨论】:

  • 解释为什么你的答案要与众不同,摆脱“低质量答案”的标签。 (审查结束)。
【解决方案2】:

简答

A[np.triu_indices_from(A, k=1)]

长答案:

您可以使用以下方法获取矩阵中上三角形的索引:

indices = np.triu_indices_from(A)

indices
Out[1]: 
(array([0, 0, 0, 1, 1, 2], dtype=int64),
 array([0, 1, 2, 1, 2, 2], dtype=int64))

这将包括对角线索引,要排除它们,您可以将对角线偏移 1:

indices_with_offset = np.triu_indices_from(A, k=1)

indices_with_offset
Out[2]: 
(array([0, 0, 1], dtype=int64), 
 array([1, 2, 2], dtype=int64))

现在将这些与您的矩阵一起用作掩码

A[indices_with_offset]

Out[3]: 
array([2, 3, 6])

请参阅文档here

【讨论】:

    【解决方案3】:

    一种掩蔽方法 -

    def upper_tri_masking(A):
        m = A.shape[0]
        r = np.arange(m)
        mask = r[:,None] < r
        return A[mask]
    

    另一个np.triu_indices -

    def upper_tri_indexing(A):
        m = A.shape[0]
        r,c = np.triu_indices(m,1)
        return A[r,c]
    

    示例运行 -

    In [403]: A
    Out[403]: 
    array([[79, 17, 79, 58, 14],
           [87, 63, 89, 26, 31],
           [69, 34, 90, 24, 96],
           [59, 60, 80, 52, 46],
           [75, 80, 11, 61, 47]])
    
    In [404]: upper_tri_masking(A)
    Out[404]: array([17, 79, 58, 14, 89, 26, 31, 24, 96, 46])
    

    运行时测试-

    In [415]: A = np.random.randint(0,9,(5000,5000))
    
    In [416]: %timeit upper_tri_masking(A)
    10 loops, best of 3: 64.2 ms per loop
    
    In [417]: %timeit upper_tri_indexing(A)
    1 loop, best of 3: 252 ms per loop
    

    【讨论】:

    • 另一种选择,np.tru_indices_from
    • @miradulo 是的,这是另一种选择!我补充说 np.triu 主要是为了比较/完整性,因为我知道掩蔽将是这里的方法。
    • 是的,有趣的是triu_indices 比掩码慢了多少。永远感谢您的回答!
    • @miradulo Neat,以前从未见过。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2022-11-29
    • 2019-09-21
    • 2011-08-27
    相关资源
    最近更新 更多