【问题标题】:Python - find closest position and valuePython - 找到最近的位置和值
【发布时间】:2016-08-15 11:30:05
【问题描述】:

我正在尝试为给定的一对 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: too many indices”

【问题讨论】:

标签: python numpy indexing


【解决方案1】:

您可以使用比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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多