Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding False-True transitions in a numpy array

Tags:

python

numpy

Given a numpy array:

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

How do I find the number of times the values transitions from False to True? For the above example, the answer would be 2. I don't want to include transitions from True to False in the count.

From the answers to How do I identify sequences of values in a boolean array?, the following produces the indices at which the values are about to change, which is not what I want as this includes True-False transitions.

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

I know that this can be done by looping through the array, however I was wondering if there was a faster way to do this?

like image 609
DavidG Avatar asked Dec 11 '17 10:12

DavidG


2 Answers

Get one-off slices - x[:-1] (starting from the first elem and ending in second last elem) and x[1:] (starting from the second elem and going on until the end), then look for the first slice being lesser than the second one, i.e. catch the pattern of [False, True] and finally get the count 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 being False and the second one as True, the idea again being to catch that pattern of [False, True] -

(~x[:-1] & x[1:]).sum()
np.count_nonzero(~x[:-1] & x[1:])
like image 104
Divakar Avatar answered Oct 09 '22 15:10

Divakar


I kind of like to use numpy method "roll" for this kind of problems... "roll" rotates the array to left some step length : (-1,-2,...) or to right (1,2,...)

import numpy as np
np.roll(x,-1)

...this will give x but shifted one step to the left:

array([ True,  True, False, False, False, False, False,  True, False, False], 
dtype=bool)

A False followed by a True can then be expressed as:

~x & np.roll(x,-1)

array([ True, False, False, False, False, False, False,  True, False, False], 
dtype=bool)
like image 31
Martin Alexandersson Avatar answered Oct 09 '22 14:10

Martin Alexandersson