Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python—在二维空间中查找最近点的有效方法_Python - Fatal编程技术网

python—在二维空间中查找最近点的有效方法

python—在二维空间中查找最近点的有效方法,python,Python,我有100个站点和点A(x,y) 我需要找到离A最近的车站。我找到了解决方案,但它抛出了一个错误 以下是我所做的: def closest_node(node, listStation): nodes = [] for i in xrange(1,len(listStation)): nodes.append((listStation[i][12],listStation[i][13])) nodes = np.asarray(nodes) dist_2 =

我有100个站点和点A(x,y)
我需要找到离A最近的车站。我找到了解决方案,但它抛出了一个错误

以下是我所做的:

def closest_node(node, listStation):
   nodes = []
   for i in xrange(1,len(listStation)):
       nodes.append((listStation[i][12],listStation[i][13]))
   nodes = np.asarray(nodes)
   dist_2 = np.sum((nodes - node)**2, axis=1)
   return np.argmin(dist_2)

print closest_node(((99,100)), listStation)
下面是错误:

dist_2 = np.sum((nodes - node)**2, axis=1)
TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'tuple'
感谢@WeaselFox,不同之处在于我从CSV文件中获得了数据。以下是解决方案:

def closest_node(node, listStation):
  nodes = []
  for i in xrange(1,len(listStation)):
      a = np.asanyarray((float(listStation[i][12]),float(listStation[i][13])))
      nodes.append(a)        

  nodes = np.asarray(nodes)    
  dist_2 = np.sum((nodes - node)**2, axis=1)
  return np.argmin(dist_2)

您需要将节点强制转换为np数组,以便numpy计算距离:

node = np.asarray(node)
例如:

>>> a = np.asarray((1,2))
>>> b = np.asarray((2,3))
>>> c = np.asarray((1,1))
>>> nodes = [b,c]
>>> dist_2 = np.sum((a - nodes)**2, axis=1)
>>> nodes[np.argmin(dist_2)]
array([1, 1])

你能先把它(节点)列成一个列表吗。因为它不断抛出一个错误“不支持的操作数类型-:'numpy.ndarray'和'numpy.ndarray'”,这很奇怪,numpy数组有一个
\uuu sub\uuu
方法。请用当前代码更新您的问题。此外,如Iv'e所示,该代码非常适用于numpy阵列。什么类型是
listStation[i][12]
listStation[i][13]
?如果答案是字符串,则在转换为nParray之前将其强制转换为int。