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

Question:

  • I have an array that looks like this: [1,2,4,1,2,5,1,2,6]
  • Given a value of 3
  • I want to find all value-pairs in the list above that encapsulate that given value.
    i.e; [2,4];[2,5];[2,6]

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.

Asked By: Skobo Do

||

Answers:

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])
Answered By: MangoNrFive
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.