简体   繁体   中英

Python - find closest position and value

I m trying to find the closest point for a couple X and Y given as to access to its values. In my case, in X directions (np.arrange(0,X.max(),1), i would like to extract the closest values from Y = 0 to obtain its values in "values array" :

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]

But i obtained an error : "IndexError: too many indices"

You can use something faster than a for loop:

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

This function will return the index of the nearest value in the array provided (such that we don't use global variables). Note that this is search in a 1D array, just like you have for X and Y .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM