Double Binary Matrix - Get Rows and Columns of True Elements

I have a binary multidimensional 2D array let's say

import numpy as np
arr = np.array([
#   Col 0   Col 1  Col 2
    [False, False, True],  # Row 0
    [True, False, False],  # Row 1
    [True, True, False],  # Row 2
])

I need a row and column for each element Truein the matrix:

[(0, 2), (1, 0), (2, 0), (2, 1)]

I know I can do this through iteration:

links = []
nrows, ncols = arr.shape
for i in xrange(nrows):
    for j in xrange(ncols):
        if arr[i, j]:
            links.append((i, j))

Is there a faster or more intuitive way?

+4
source share
1 answer

Are you looking for np.argwhere-

np.argwhere(arr)

Run Example -

In [220]: arr
Out[220]: 
array([[False, False,  True],
       [ True, False, False],
       [ True,  True, False]], dtype=bool)

In [221]: np.argwhere(arr)
Out[221]: 
array([[0, 2],
       [1, 0],
       [2, 0],
       [2, 1]])
+7
source

Source: https://habr.com/ru/post/1625897/


All Articles