I have 2 NumPy array as follow:
import numpy as np
a = np.array([1, 4, 2, 6, 4, 4, 6, 2, 7, 6, 2, 8, 9, 3, 6, 3, 4, 4, 5, 8])
b = np.array([2, 8, 3, 9, 9, 9, 7, 5, 4, 8, 6, 5, 4, 4, 7, 2, 1, 1, 9, 9])
and 2 constant numbers:
c = 6
d = 3
Based on a previous question, I can extract an array each times the elements in a
are less than c
, 2 or more times consecutively:
array = np.append(a, -np.inf) # padding so we don't lose last element
mask = array >= c # values to be removed
split_indices = np.where(mask)[0]
for subarray in np.split(array, split_indices + 1):
if len(subarray) > 2:
print(subarray[:-1])
which output:
[1. 4. 2.]
[4. 4.]
[3. 4. 4. 5.]
Now, I would like to change my condition for a multiple condition where, 2 or more times consecutively:
- elements in
a
are less thanc
,
AND
- elements in
b
are less thand
Using the following code:
mask = ((a< c) & (b< d))
I know that my conditions (2 times or more consecutively) are just meet 1 time at indices 15
,16
and 17
.
Now I would like to extract the value of a
corresponding to those indices where my conditions are meet.
Based on the link answer, I tried:
a1= np.append(a, -np.inf)
a2=np.append(b, -np.inf) # padding so we don't lose last element
mask = ((a1< c) & (a2< d)) # values to be removed
split_indices = np.where(mask)[0]
for subarray in np.split(a, split_indices + 1):
if len(subarray) > 2:
print(subarray[:-1])
Which surprisingly, return an array where my coonditions are not meet...
[4 2 6 4 4 6 2 7 6 2 8 9 3 6]
I also tried the np.extract
as follow:
np.extract((len(list(g))>=2 for i, g in ((a < c) & (b < d)) if i), a)
which return me a value of 1
and not the value of the array a
...
The desired output array should be the one of indice 15
,16
,17
corresponding to the value [3 4 4]
in array a
.
Could someone point me to the python tools I could use in order to extract the array fulfilling my multiple conditions?
NOTE: this is a minimal example of my problem, in my "real life" I need to find arrays that meet my conditions 14 times or more consecutively!