Finding False-True transitions in a numpy array

Given a numpy array:

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

How to find the number of transitions between False and True? In the above example, the answer will be 2. I do not want to include the transitions from True to False in the score.

From the answers to How to determine the sequence of values ​​in a Boolean array? , below are the indexes whose values ​​will be changed, which is not what I want, as this includes True-False transitions.

 np.argwhere(np.diff(x)).squeeze() # [0 2 7 8] 

I know this can be done by going through an array, however I was wondering if there is a faster way to do this?

+5
source share
1 answer

Get one-time fragments - x[:-1] (starting from the first element and ending with the second second element) and x[1:] (starting from the second element and continuing to the end), then find the first cut, smaller than the second, i.e. catch the pattern [False, True] and finally get a counter with ndarray.sum() or np.count_nonzero() -

 (x[:-1] < x[1:]).sum() np.count_nonzero(x[:-1] < x[1:]) 

Another way would be to look for the first slice of False , and the second as True , the idea again was to catch this pattern [False, True] -

 (~x[:-1] & x[1:]).sum() np.count_nonzero(~x[:-1] & x[1:]) 
+8
source

Source: https://habr.com/ru/post/1273977/


All Articles