Skip to content

Instantly share code, notes, and snippets.

@kidpixo
Last active January 28, 2020 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kidpixo/67ee8c3bcc00cbb0f9d81a60b30387ee to your computer and use it in GitHub Desktop.
Save kidpixo/67ee8c3bcc00cbb0f9d81a60b30387ee to your computer and use it in GitHub Desktop.
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