我有两个2d numpy数组:x_array包含x方向的位置信息,y_array包含y方向的位置.
然后我有一长串x,y点.
对于列表中的每个点,我需要找到最接近该点的位置(在数组中指定)的数组索引.
基于这个问题,我天真地产生了一些有效的代码: 在numpy数组中查找最接近的值
即
import time
import numpy
def find_index_of_nearest_xy(y_array, x_array, y_point, x_point):
distance = (y_array-y_point)**2 + (x_array-x_point)**2
idy,idx = numpy.where(distance==distance.min())
return idy[0],idx[0]
def do_all(y_array, x_array, points):
store = []
for i in xrange(points.shape[1]):
store.append(find_index_of_nearest_xy(y_array,x_array,points[0,i],points[1,i]))
return store
# Create some dummy data
y_array = numpy.random.random(10000).reshape(100,100)
x_array = numpy.random.random(10000).reshape(100,100)
points = numpy.random.random(10000).reshape(2,5000)
# Time how long it takes to run
start = time.time()
results = do_all(y_array, x_array, points)
end = time.time()
print 'Completed in: ',end-start
Run Code Online (Sandbox Code Playgroud)
我在一个大型数据集上做这个,并且真的想加快一点.谁能优化这个?
谢谢.
更新:解决方案遵循@silvado和@justin的建议(下) …