Reputation: 787
I'm trying to find the locations in an array where the values increase monotonically such that the total change in value is greater than k.
Ie for k = 5
and data = [1, 4, 5, 7, 10, 9, 6, 14, 3, 4]
I would want to return:
[4, 7]
In general the array would be floats.
Edit to further clarify: In the example the data values increase monotonically by greater than 5 in two intervals. The first is from element 0 to 4 (where the data values increase by 9), the 2nd is from element 6 to 7 (where the data values increase by 8). Thus, I want to report the end of each valid interval.
I want to avoid loops and make this efficient. If necessary the range of consecutive values to check could be limited.
Upvotes: 0
Views: 871
Reputation: 221624
Here's a vectorized approach -
d = a[1:] - a[:-1]
mask = np.concatenate(( [False], d > 0, [False] ))
start = np.flatnonzero(mask[1:] > mask[:-1])
stop = np.flatnonzero(mask[1:] < mask[:-1])
count = np.bincount(np.repeat(np.arange(start.size) ,stop - start), d[mask[1:-1]])
out = stop[count > k]
Sample input, output -
In [202]: a # Adding in two monotonically decreasing elems at start for variety
Out[202]: array([10, 7, 1, 4, 5, 7, 10, 9, 6, 14, 3, 4])
In [203]: k = 5
In [204]: out
Out[204]: array([6, 9])
Upvotes: 2