Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get indices of non-diagonal elements of a numpy array?

Tags:

python

numpy

How to get indices of non-diagonal elements of a numpy array?

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

I tried as follows:

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

After that, no idea... The expected result should be:

result = [[False, True, True],
        [True, False, True],
         [True, True, False]]
like image 724
gudlife Avatar asked Mar 02 '16 12:03

gudlife


1 Answers

To get the mask, you can use np.eye, like so -

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

To get the indices, add np.where -

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

Sample run -

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]))

There are few more ways to get such a mask for a generic non-square input array.

With np.fill_diagonal -

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

With broadcasting -

m,n = a.shape
out = np.arange(m)[:,None] != np.arange(n)
like image 196
Divakar Avatar answered Oct 11 '22 13:10

Divakar