问题描述
您正在寻找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]])
解决方法
我有一个二进制的numpy 2D数组,例如,
import numpy as np
arr = np.array([
# Col 0 Col 1 Col 2
[False,False,True],# Row 0
[True,False],# Row 1
[True,True,# Row 2
])
我想要True
矩阵中每个元素的行和列:
[(0,2),(1,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))
有没有更快或更直观的方法?