Skip to content Skip to sidebar Skip to footer

Numpy Array Crossing 2 Values And Gets The Index

I am trying to code a function where it gives me the indexes of where the values of lower or upper either gets crossed or touched by a. I want to get the crosses in order, so the

Solution 1:

What I don't quite get is that the first two crossings are lower crossings: one on the lower bound, and another on the upper bound.

Anyhow, we can work on the two bounds separately regardless. This method uses a combination of np.logical_or and np.roll, as well as np.nonzero to retrieve the indices.

The array mask is given by:

>>>mask_b = np.logical_or(
      np.logical_or((a < b)*(np.roll(a, -1) > b), 
                    (a > b)*(np.roll(a, -1) < b)),
      a == b)

>>>mask_b.nonzero()[0]
array([ 7,  9, 12, 13, 17, 18])

Looking at a single bound, here the upper bound we have the data crossing it as 0, 1, 0, 1, 0, and 1.

Similarly for the lower bound c:

>>> mask_c = np.logical_or(
      np.logical_or((a <c)*(np.roll(a,-1)>c),(a >c)*(np.roll(a,-1)<c)),
      a ==c)>>> mask_c.nonzero()[0]
array([0,13,17,18])

Here again, we have 0, 1, 0, and 1 crossings.

You can check this matches well with the following plot I sent:

enter image description here

Post a Comment for "Numpy Array Crossing 2 Values And Gets The Index"