Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter Numpy Array for Values Greater than Preceding Value

Given the following array how can I filter to produce a new array that contains the values that are less than the next value by at least 3?

In other words, I need to compare each value with its neighbour on the right and add it to a new array if that neighbour is higher by 3 or more.

ex_arr = [1, 2, 3, 8, 9, 10, 12, 16, 17, 23]

desired_arr = [3, 12, 17]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use diff to compare the successive values and form a boolean mask, add a False to this array (with np.r_) to account for the last value and perform boolean indexing:

ex_arr = np.array([1, 2, 3, 8, 9, 10, 12, 16, 17, 23])

desired_arr = ex_arr[np.r_[np.diff(ex_arr)>=3, False]]

Or using numpy.nonzero:

desired_arr = ex_arr[np.nonzero(np.diff(ex_arr)>=3)[0]]

Output: array([ 3, 12, 17])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading