For a scalar, let's say I have the following levels
levels_ = [5, 6, 7, 8, 9, 10]
and the function
import numpy as np
def find_level(x, levels):
levels = np.asarray(levels)
if x <= levels.min() or x >= levels.max():
idx = (np.abs(levels - x)).argmin()
else:
idx = np.argmax(levels > x) - 1
return levels[idx]
The function will return the nearest value where x>value from the ordered values of the levels and within the lower and upper boundaries as well.
find_level(x=0.5, levels=levels_) # will return 5
find_level(x=7.01, levels=levels_) # will return 7
find_level(x=7.50, levels=levels_) # will return 7
find_level(x=7.99, levels=levels_) # will return 7
find_level(x=15, levels=levels_) # will return 10
I would like to pass an array x of any size and obtain an array of the same size with the same computation for every value of the array. For example, with the following input:
x_ = np.array([[0.5, 7.01, 7.50, 7.99, 15],
[20, 30, 6.26, 5.01, 6.54]])
, the function find_level_multi(x=x_, levels=levels_) would the return the following output:
np.array([[5, 7, 7, 7, 10],
[10, 10, 6, 5, 6]])
I could loop through every row and column and use the function find_level(x, levels) but it would be extremly slow for a large array so I am looking for a function that could accomplish the same task in less time.