我正在尝试找到所有距离1公里半径内的最近邻居。以下是我的脚本构建树和搜索最近点的方法:
from pysal.cg.kdtree import KDTree
def construct_tree(s):
data_geopoints = [tuple(x) for x in s[['longitude','latitude']].to_records(index=False)]
tree = KDTree(data_geopoints, distance_metric='Arc', radius=pysal.cg.RADIUS_EARTH_KM)
return tree
def get_neighbors(s,tree):
indices = tree.query_ball_point(s, 1)
return indices
#Constructing the tree for search
tree = construct_tree(data)
#Finding the nearest neighbours within 1KM
data['neighborhood'] = data['lat_long'].apply(lambda row: get_neighbors(row,tree))
根据我在pysal页面阅读到的内容,它说 -
在scipy的kd-tree功能之上构建了kd-tree。 如果使用scipy 0.12或更高版本,则使用scipy.spatial.cKDTree,否则使用scipy.spatial.KDTree。
在我的情况下,应该使用cKDTree。 对于示例数据集,这很好地工作,但由于tree.query_ball_point
将索引列表作为结果返回。每个列表将有数百个元素。对于我的数据点(200万条记录),这越来越大,并且在某些点上由于内存问题而停止。如何解决呢?