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

use*_*754 0 python indexing numpy

我试图找到给定的 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]
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:“IndexError:索引太多”

Jol*_*orc 5

您可以使用比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
Run Code Online (Sandbox Code Playgroud)

该函数将返回所提供数组中最接近值的索引(这样我们就不会使用全局变量)。请注意,这是在一维数组中的搜索,就像 forX和一样Y