[英]Search elements in two arrays in the given range using numpy.where()
我正在處理大量的地球物理數據。 我有兩個大小為320x340的numpy數組:第一個XLAT
包含網格中每個點的緯度,第二個XLON
包含網格中每個點的經度。 所以每個i, j
用緯度XLAT[i][j]
和經度XLON[i][j]
描述地面上的點。
我有坐標P_LAT
和P_LON
,我必須找到最接近給定點的4點。
首先,我編寫了簡單的函數,它貫穿x軸和y軸上的所有點,但它使得320 * 340 = 108 800次迭代並且工作非常慢(每點約0.5秒):
for i in range(0, lat-1):
for j in range(0, lon-1):
if ST_LON >= XLON[i][j] and \
ST_LON < XLON[i][j + 1] and \
ST_LAT >= XLAT[i][j] and \
ST_LAT < XLAT[i + 1][j]:
return (True, i, i + 1, j, j + 1)
然后我找到了一些關於numpy.where()
並編寫了這段代碼:
for i in range(0, lat):
rows = numpy.where((XLON[i] >= ST_LON - 0.5) & (XLON[i] <= ST_LON + 0.5))
for j in rows[0]:
if ST_LON >= XLON[i][j] and \
ST_LON < XLON[i][j + 1] and \
ST_LAT >= XLAT[i][j] and \
ST_LAT < XLAT[i + 1][j]:
return (True, i, i + 1, j, j + 1)
這個功能工作得更快(每點約0.015秒),但我認為這不是正確而美觀的解決方案。
所以我的最后一個問題是如何在兩個數組中找到滿足條件的項:
XLON[i] <= ST_LON <= XLON[i][j+1]
和XLAT[i][j] <= ST_LAT <= XLAT[i+1][j]
這應該很快?
我不確定編程任務,所以讓我用自己的話重復一遍:
你有兩個2dim陣列XLAT和XLON。 它們是某種平移陣列,用於從某個網格獲取緯度/經度。
從你的代碼示例中我得出結論: XLON [i] [j] == XLON [h] [j]對所有i,h在范圍(0,lat)中有效嗎? (也許有一個很好的理由擁有那個對象,但它看起來並不高效)
因此,最簡單的解決方案應該是單獨處理機器人尺寸:
for i in range(0, lat-1):
if (XLON[i][0] >= ST_LON - 0.5) & (XLON[i][0] <= ST_LON + 0.5):
break
for 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, i + 1, j, j + 1)
您還可以使用np.where替換if-break語句。
我不確定我是否幫助你。 如果我的回答沒有幫助,那么向我們提供一個帶有XLON的小型工作示例python代碼是非常有用的,XLAT簡化為5x4維度。
感謝所有的回復,我找到了一個快速的解決方案,使用numpy.where()
條件numpy.where()
,但它有點不漂亮,不美觀:)
#Calculate the step
dLAT = numpy.abs(self.XLON[0][1] - self.XLON[0][0]) * 3
dLON = numpy.abs(self.XLAT[1][0] - self.XLAT[0][0]) * 3
#Get the rows and cells satisfying the condition
rows, cells = numpy.where(((self.XLON >= ST_LON - dLON) & (self.XLON <= ST_LON + dLON)) & ((self.XLAT >= ST_LAT - dLAT) & (self.XLAT <= ST_LAT + dLAT)))
#Loop through all the values
for i in range(0, len(rows)):
#Get the indexes
current_lat = rows[i]
next_lat = rows[i] + 1
current_lon = cells[i]
next_lon = cells[i] + 1
#Check the point
if ST_LON >= self.XLON[current_lat][current_lon] and ST_LON < self.XLON[current_lat][next_lon] and \
ST_LAT >= self.XLAT[current_lat][current_lon] and ST_LAT < self.XLAT[next_lat][current_lon]:
return(True, current_lat, next_lat, current_lon, next_lon)
return (False, 0, 0, 0, 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.