假设我有以下矩阵:
A = np.array([
[1,2,3],
[4,5,6],
[7,8,9]])
如何在没有对角线的情况下有效提取上三角矩阵? 输出将是以下数组:
B = np.array([2,3,6])
答案 0 :(得分:10)
掩盖的一种方法 -
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
答案 1 :(得分:0)
简短回答
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
答案 2 :(得分:0)
np.triu(A, k=1)
indices = np.where(np.triu(np.ones(A.shape), k=1).astype(bool))
print(A[x])
[2 3 6]