numpy: search of the first and last index in an ar

2019-07-14 07:18发布

I use Python with numpy.

I have a numpy array b:

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

I need to find the first and last index where b is equal True.

For this exsample:

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

Can someone please suggest, how do I get out_index?

1条回答
▲ chillily
2楼-- · 2019-07-14 07:32
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

output:

[[ 0  2]
 [ 5  6]
 [ 8 11]]
查看更多
登录 后发表回答