Last active
January 28, 2020 14:37
-
-
Save kidpixo/67ee8c3bcc00cbb0f9d81a60b30387ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_nearest(value, | |
array, | |
return_value=False): | |
"""Find nearest value in a numpy array | |
Parameters | |
---------- | |
value : value to search for | |
array : array to search in, should be sorted. | |
return_value : bool, if to return the actual values | |
Returns | |
------- | |
""" | |
##TODO add sorting check/option to sort ? make sense? | |
import numpy as np | |
closest_index = (np.abs(array - value)).argmin() | |
if value > np.nanmax(array): | |
import warnings | |
warnings.warn(f'value > np.nanmax(array) : {value} > {np.nanmax(array)}') | |
if value < np.nanmin(array): | |
import warnings | |
warnings.warn(f'value < np.nanmin(array) : {value} < {np.nanmax(array)}') | |
if not return_value: | |
return closest_index | |
else: | |
return closest_index, array[closest_index] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment