Home > OS >  np.array index slicing bethween conditions
np.array index slicing bethween conditions

Time:10-15

I need to slice an array's index from where a first condition is true to where a second condition is true, these conditions are never true at the same time, but one can be true more than one time before the other occurs.
I try to explain:

array_filter = np.array([3,4,5,6,4,3,2,3,4,5])
array1 = np.array([2,3,4,6,3,3,1,2,3,4])
array2 = np.array([3,5,6,7,5,4,3,3,5,6])

array1_cond = array1 >= array_filter
array2_cond = array2 <= array_filter


                0  1  2   3  4  5  6   7  8  9
array_filter    3  4  5   6  4  3  2   3  4  5 
array1          2  3  4   6  3  3  1   2  3  4
array1_cond               ^     ^               (^ = True)
array2          3  5  6   7  5  4  3   3  5  6    
array2_cond     ^                      ^ 

expected_output 2  3  4 | 7  5  4  3 | 2  3  4
                 array1 |   array2   | array1

EXPECTED OUTPUT:

expected_output[(array2_cond) : (array1_cond)] = array1[(array2_cond) : (array1_cond)]
expected_output[(array1_cond) : (array2_cond)] = array2[(array1_cond) : (array2_cond)]
expected_output = [ 2, 3, 4, 7, 5, 4, 3, 2, 3, 4 ]
       

I'm so sorry if syntax is a little confusing, but idk how to make it better... <3
How can I perform this?
Is it possible WITHOUT LOOPS?

CodePudding user response:

This works for your example, with a, b in place of array1, array2:

nz = np.flatnonzero(a_cond | b_cond)
lengths = np.diff(nz, append=len(a))
cond = np.repeat(b_cond[nz], lengths)
result = np.where(cond, a, b)

If at the start of the arrays neither condition holds true then elements from b are selected.

  • Related