根据元素与某点的距离对二维numpy数组排序
我有一个(n,2)的numpy数组,这个数组里存放了n个点的坐标。现在我想根据每个点到某个特定点(x,y)的距离来对这些点进行排序,并找出离这个点最近的那个。请问我该怎么做呢?
目前我有:
def find_nearest(array,value):
xlist = (np.abs(array[:, 0]-value[:, 0]))
ylist = (np.abs(array[:, 1]-value[:, 1]))
newList = np.vstack((xlist,ylist))
// SORT NEW LIST and return the 0 elemnt
在我的解决方案中,我需要根据离(0,0)的距离来对newList进行排序,但我不知道该怎么做?有没有什么解决办法或者其他的方案呢?
我的点的数组看起来是这样的:
array([[ 0.1648, 0.227 ],
[ 0.2116, 0.2472],
[ 0.78 , 0.546 ],
[ 0.9752, 1. ],
[ 0.384 , 0.4862],
[ 0.4428, 0.2204],
[ 0.4448, 0.4146],
[ 0.1046, 0.2658],
[ 0.5668, 0.7792],
[ 0.1664, 0.0746],
[ 0.5636, 0.6372],
[ 0.7822, 0.5536],
[ 0.7718, 0.8276],
[ 0.9916, 1. ],
[ 0. , 0. ],
[ 0.8206, 0.817 ],
[ 0.4858, 0.4652],
[ 0. , 0. ],
[ 0.1574, 0.3114],
[ 0. , 0.0022],
[ 0.874 , 0.714 ],
[ 0.148 , 0.6624],
[ 0.0656, 0.5912],
[ 0.1148, 0.607 ],
[ 0.069 , 0.6296]])
4 个回答
0
那我们可以直接在 sorted
函数里用一个叫做 key 的参数来处理吗?
sorted(p, key = lambda (a,b) :(a-m)**2+(b-n)**2)
这里的 p
是一个数组,像这样 array([[1,2], [3,4], ...])
,而 (m,n)
是表示最慢点的一个元组……
2
如果你安装了scipy,下面的代码可以正常运行:
import scipy.spatial.distance as ds
import numpy as np
pointOfInterest = np.array([[0, 0]])
然后:
arr[ds.cdist(pointOfInterest, arr)[0].np.argsort()[0]]
arr
就是你上面提到的数组。
6
为了找到最近的点,排序并不是个好主意。如果你想找最近的点,那就直接找最近的点就行了,排序太浪费时间了。
def closest_point(arr, x, y):
dist = (arr[:, 0] - x)**2 + (arr[:, 1] - y)**2
return arr[dist.argmin()]
而且,如果你需要多次在一组固定或几乎固定的点中进行搜索,有一些特定的数据结构可以大大加快这种查询的速度(搜索时间会变得比线性时间更快)。
2
如果你只想计算直角坐标系中的距离,可以这样做:
def find_nearest(arr,value):
newList = arr - value
sort = np.sum(np.power(newList, 2), axis=1)
return newList[sort.argmin()]
我假设 newList
的形状是 (n,2),也就是说它有 n 行和 2 列。顺便提一下,我把输入变量 array
改成了 arr
,这样可以避免在使用像 from numpy import *
这样的导入方式时出现问题。