我正在尝试查找距离1 KM范围内的所有最近邻居。这里是我的脚本来构建树和搜索最近点,优化scipy最近邻居搜索
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页面读取,它说 -
kd树建在SciPy的的kd树的功能之上。如果使用scipy 0.12或更高版本使用scipy.spatial.cKDTree,否则使用scipy.spatial.KDTree。
在我的情况下,它应该使用cKDTree。这对于示例数据集工作正常,但由于tree.query_ball_point
返回索引列表作为结果。每个列表将有100个元素。对于我的数据点(200万条记录),这个数字越来越大,并且在某个点之后由于内存问题而停止。任何想法如何解决这个问题?
您是否考虑过将“邻居”数据存储在DataFrame中?想到“networkx.Graph”。 –
抱歉没有听说过它。你能写一个例子吗?我可以尝试,可能是。 –
https://networkx.github.io/是一个用于处理图形数据的库。在你的情况下,我会将位置标识存储为顶点,并在相距不到1公里的位置之间添加边。该文档包含一个很好的教程。 –