Numpy 二进制矩阵 - 获取 True 元素的行和列



我有一个二进制 numpy 2D 数组,比如说,

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

我想要矩阵中每个True元素的行和列:

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

我知道我可以通过迭代来做到这一点:

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

有没有更快或更直观的方法?

您正在寻找np.argwhere -

np.argwhere(arr)

示例运行 -

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

最新更新