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

gud*_*ife 7 python numpy

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

a = np.array([[7412, 33, 2],
              [2, 7304, 83],
              [3, 101, 7237]])
Run Code Online (Sandbox Code Playgroud)

我尝试如下:

diag_indices = np.diag_indices_from(a)
print diag_indices
(array([0, 1, 2], dtype=int64), array([0, 1, 2], dtype=int64))
Run Code Online (Sandbox Code Playgroud)

在那之后,不知道......预期的结果应该是:

result = [[False, True, True],
        [True, False, True],
         [True, True, False]]
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 10

要获得面具,你可以np.eye像这样使用-

~np.eye(a.shape[0],dtype=bool)
Run Code Online (Sandbox Code Playgroud)

要获得指数,请添加np.where-

np.where(~np.eye(a.shape[0],dtype=bool))
Run Code Online (Sandbox Code Playgroud)

样品运行 -

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]))
Run Code Online (Sandbox Code Playgroud)

对于通用非方形输入数组,有更多方法可以获得这样的掩码.

随着np.fill_diagonal-

out = np.ones(a.shape,dtype=bool)
np.fill_diagonal(out,0)
Run Code Online (Sandbox Code Playgroud)

随着broadcasting-

m,n = a.shape
out = np.arange(m)[:,None] != np.arange(n)
Run Code Online (Sandbox Code Playgroud)