Issue
Consider the 1D array arr
shown below, and assume n = 3
.
I want to identify all 'islands' holding >= n consecutive positive values.
The following code succesfully finds the FIRST set of 3 consecutive positive numbers by determining the initial index, but it does not find all such sets.
import numpy as np
arr = np.array([1, -1, 5, 6, 3, -4, 2, 5, 9, 2, 1, -6, 8])
def find_consec_pos(arr, n):
mask = np.convolve(np.greater(arr,0), np.ones(n, dtype=int)) >= n
if mask.any():
return mask.argmax() - n + 1
else:
return None
find_consec_pos(arr, 3)
This gives output 2
, the index of the 1st triplet of consecutive positive values.
I want to know how to modify the code to get the output [2, 6, 7, 8]
, identifying all consecutive positive triples.
Solution
You could use sliding_window_view
:
In [1]: from numpy.lib.stride_tricks import sliding_window_view
In [2]: sliding_window_view(arr, 3) > 0
Out[2]:
array([[ True, False, True],
[False, True, True],
[ True, True, True],
[ True, True, False],
[ True, False, True],
[False, True, True],
[ True, True, True],
[ True, True, True],
[ True, True, True],
[ True, True, False],
[ True, False, True]])
Turning this into your desired function (and assuming you want a list
as output):
def find_consec_pos(arr, n):
all_n_positive = np.all(sliding_window_view(arr > 0, n), axis=1)
return np.argwhere(all_n_positive).flatten().tolist()
Demo of some different "window" sizes:
In [4]: arr
Out[4]: array([ 1, -1, 5, 6, 3, -4, 2, 5, 9, 2, 1, -6, 8])
In [5]: find_consec_pos(arr, 3)
Out[5]: [2, 6, 7, 8]
In [6]: find_consec_pos(arr, 4)
Out[6]: [6, 7]
In [7]: find_consec_pos(arr, 2)
Out[7]: [2, 3, 6, 7, 8, 9]
Answered By - ddejohn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.