pythonnumpybisect

How to find all lower and upper values for a given value in a list


I can find the [2,6] values by using bisect, but how can I find all the values?

x = np.array([1,2,4,1,2,5])
xL = bisect_left(x,start)-1
xU = bisect_left(x,start)
print(xL ," ", xU)
lower = x[xL]
upper = x[xU]
print(lower, upper)

P.S. My actual data is quite large, so I do not think writing the code by myself with for loops etc. is a valid approach, so I want to mainly use build in libraries like pandas etc.


Solution

  • You could do something like this:

    import numpy as np
    
    
    x = np.array([1, 2, 4, 1, 2, 5, 1, 2, 6])
    
    x_left = x[:-1]
    x_right = x[1:]
    
    encapsulation = np.where((x_left < 3) & (x_right > 3))
    left_encapsulation_values = x_left[encapsulation]
    right_encapsulation_values = x_right[encapsulation]
    

    You have one array for the left values (doesn't contain the last element, because it doesn't have a right neighbor) and an array for the right values (without the first element, same idea). Then you mask those arrays with the condition that you defined and voila you have the left and right values that do encapsulate 3.

    left_encapsulation_values=array([2, 2, 2])
    right_encapsulation_values=array([4, 5, 6])