Reputation: 307
I have 100 stations and point A(x,y)
I need to find the nearest station to A. I found the solution here, but it throws an error.
Here is what I did:
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)
And here is the error:
dist_2 = np.sum((nodes - node)**2, axis=1)
TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'tuple'
Thanks to @WeaselFox, the difference is I got the data from CSV file. here is the solution:
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)
Upvotes: 0
Views: 202
Reputation: 7380
you need to cast your node to an np array for numpy to calculate the distance:
node = np.asarray(node)
example:
>>> 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])
Upvotes: 1