簡體   English   中英

Python-查找最接近的位置和值

[英]Python - find closest position and value

我試圖找到給定的X和Y的最接近點,以獲取其值。 就我而言,在X方向上(np.arrange(0,X.max(),1),我想從Y = 0中提取最接近的值,以在“值數組”中獲取其值:

import numpy as np
import matplotlib.pyplot as plt
#My coordinates are given here :
X = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4 ,5, 0, 1, 2, 3, 4 ,5])
Y = np.array([-2.5, -1.5, 0, 0, 2, 2.5, 2, 1.5, 1, -1, -1.2,-2.5, 0.2, 0.5, 0, -0.5, -0.1,0.05])
plt.scatter(X,Y);plt.show()
#The corresponding values are :
values = np.array([-1.1, -9, 10, 10, 20, 25, 21, 15, 0, 2, -2,-5, 2, 50, 0, -5, -1,5])


# I thought to use a for loop : 

def find_index(x,y):
    xi=np.searchsorted(X,x)
    yi=np.searchsorted(Y,y)
    return xi,yi

 for i in arange(float(0),float(X.max()),1):
      print i
      thisLat, thisLong = find_index(i,0)
      print thisLat, thisLong
      values[thisLat,thisLong]

但是我得到了一個錯誤:“ IndexError:索引太多”

您可以使用比for循環更快的速度:

import numpy as np

def find_nearest(array, value):
    ''' Find nearest value is an array '''
    idx = (np.abs(array-value)).argmin()
    return idx

haystack = np.arange(10)
needle = 5.8

idf = find_nearest(haystack, needle)
print haystack[idf] # This will return 6

此函數將返回提供的數組中最接近的值的索引(這樣我們就不會使用全局變量)。 請注意,這是在1D數組中進行搜索,就像在XY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM