NumPy:在数组中查找第一个和最后一个索引

3

我使用带有 numpy 的 Python。

我有一个 numpy 数组 b:

b = np.array([True,True,True,False,False,True,True,False,True,True,True,True,False])

我需要找到第一个和最后一个位置,其中 b 等于 True

对于此示例:

out_index: [0,2]
           [5,6]
           [8,11]

请问有人能建议一下,我该如何获取out_index

1个回答

6
b = np.array([True,True,True,False,False,True,True,False,True,True,True,True,False])
idx = np.argwhere(np.diff(np.r_[False, b, False])).reshape(-1, 2)
idx[:, 1] -= 1
print idx

输出:

[[ 0  2]
 [ 5  6]
 [ 8 11]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接