Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 877
Olga Avatar asked Jan 29 '26 19:01

Olga


1 Answers

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]]
like image 163
HYRY Avatar answered Feb 01 '26 09:02

HYRY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!