如何获得numpy数组的非对角元素的索引?

时间:2016-03-02 12:07:33

标签: python numpy

如何获取numpy数组的非对角线元素的索引?

a = np.array([[7412, 33, 2],
              [2, 7304, 83],
              [3, 101, 7237]])

我尝试如下:

diag_indices = np.diag_indices_from(a)
print diag_indices
(array([0, 1, 2], dtype=int64), array([0, 1, 2], dtype=int64))

之后,不知道...... 预期结果应为:

result = [[False, True, True],
        [True, False, True],
         [True, True, False]]

3 个答案:

答案 0 :(得分:9)

要获取掩码,您可以使用np.eye,如此 -

~np.eye(a.shape[0],dtype=bool)

要获取索引,请添加np.where -

np.where(~np.eye(a.shape[0],dtype=bool))

示例运行 -

In [142]: a
Out[142]: 
array([[7412,   33,    2],
       [   2, 7304,   83],
       [   3,  101, 7237]])

In [143]: ~np.eye(a.shape[0],dtype=bool)
Out[143]: 
array([[False,  True,  True],
       [ True, False,  True],
       [ True,  True, False]], dtype=bool)

In [144]: np.where(~np.eye(a.shape[0],dtype=bool))
Out[144]: (array([0, 0, 1, 1, 2, 2]), array([1, 2, 0, 2, 0, 1]))

为通用非正方形输入数组提供此类掩码的方法还有很多。

使用np.fill_diagonal -

out = np.ones(a.shape,dtype=bool)
np.fill_diagonal(out,0)

使用broadcasting -

m,n = a.shape
out = np.arange(m)[:,None] != np.arange(n)

答案 1 :(得分:2)

>>> import numpy as np
>>> a = np.array([[7412, 33, 2],
...               [2, 7304, 83],
...               [3, 101, 7237]])
>>> non_diag = np.ones(shape=a.shape, dtype=bool) - np.identity(len(a)).astype(bool)
>>> non_diag
array([[False,  True,  True],
       [ True, False,  True],
       [ True,  True, False]], dtype=bool)

答案 2 :(得分:0)

作为先前答案的另一种思路,您可以选择下三角的索引:

a = np.array([[7412, 33, 2],
              [2, 7304, 83],
              [3, 101, 7237]])
# upper triangle. k=1 excludes the diagonal elements.
xu, yu = np.triu_indices_from(a, k=1)
# lower triangle
xl, yl = np.tril_indices_from(a, k=-1)  # Careful, here the offset is -1

# combine
x = np.concatenate((xl, xu))
y = np.concatenate((yl, yu))

doc中所述,然后可以使用它们来索引和分配值:

out = np.ones((3,3), dtype=bool)
out[(x, y)] = False

给予:

>>> out
array([[ True, False, False],
   [False,  True, False],
   [False, False,  True]])
相关问题