[GIS] Nearest numpy array element whose value is less than the current element

arcgis-10.4arcpynumpy

I'm using ArcGIS 10.4x and Python/numpy for this question. Can anyone suggest an efficient way to determine the array location of the nearest element whose value is less than the search element? As an example, if I provide the script a row/col number of a numpy array (the element value for example = 42.5), what is the most efficient way to find the row/col values for the nearest element whose value is less than the 42.5 value? I will have many source cells to iterate through and more often than not, an element with a lower value will be relatively close, so ideally I'd have a way where the search originates from the elements nearest to the source and radiates outwards until a solution is found.

Best Answer

You can do this with scipy (I hope it is included in ArcGis 10.4).

import numpy as np
from scipy.spatial.distance import cdist
a,b = np.where(array < 42.5) # get rows and columns where vlue is less than 42.5
x = zip(a,b) # create a list with (row,column)
d = np.argmin(cdist(np.array([[row,column]]), x)) # first distances are calculated between (row, col) of your input value, than nearest index value is selected
x[d] # this is result (row,col) of the nearest element under 42.5
Related Question