Issue
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]
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])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.