python - Search elements in two arrays in the given range using numpy.where() -
i'm working big arrays of geophysical data. have 2 numpy arrays have sizes 320x340: first xlat
contains latitude of every point in grid, second xlon
contains longitude of every point in grid. every i, j
describes point on ground latitude xlat[i][j]
, longitude xlon[i][j]
.
i have point coordinates p_lat
, p_lon
, have find closest 4 point given point.
first of wrote simple function run through point on x-axis , y-axis, makes 320*340 = 108 800 iterations , works very slow (~0.5 seconds every point):
in range(0, lat-1): j in range(0, lon-1): if st_lon >= xlon[i][j] , \ st_lon < xlon[i][j + 1] , \ st_lat >= xlat[i][j] , \ st_lat < xlat[i + 1][j]: return (true, i, + 1, j, j + 1)
then found info numpy.where()
, wrote code:
in range(0, lat): rows = numpy.where((xlon[i] >= st_lon - 0.5) & (xlon[i] <= st_lon + 0.5)) j in rows[0]: if st_lon >= xlon[i][j] , \ st_lon < xlon[i][j + 1] , \ st_lat >= xlat[i][j] , \ st_lat < xlat[i + 1][j]: return (true, i, + 1, j, j + 1)
this function works faster (~0.015 sec every point), don't think right , beautiful solution.
so final question how can find items in both arrays, satisfy conditions:
xlon[i] <= st_lon <= xlon[i][j+1]
, xlat[i][j] <= st_lat <= xlat[i+1][j]
and should work quickly?
i not sure programming task, let me repeat in own words:
you have 2 2dim arrays xlat , xlon. kind of translating arrays latitude / longitude grid.
from code examples conclude: xlon[i][j]==xlon[h][j] valid i,h in range(0,lat) ?! (maybe there reason have object, doesn't performant)
so simple solution should treat bot dimensions seperately:
for in range(0, lat-1): if (xlon[i][0] >= st_lon - 0.5) & (xlon[i][0] <= st_lon + 0.5): break j in range(0, lon-1): if (xlat[0][j] >= st_lat - 0.5) & (xlat[0][j] <= st_lat + 0.5)): break return (true, i, + 1, j, j + 1)
you can replace if-break statement np.where.
i not sure if got right. if answer not help, usefull supply small working example python code xlon, xlat reduced to, say, 5x4 dimensions.
Comments
Post a Comment