微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python-计算熊猫地理密度的有效方法?

我有大量的经度和纬度数据对应于美国的快餐店.对于每个快餐店,我想知道5英里范围内还有多少其他快餐店.我可以像这样使用Geopy在Pandas中进行计算(DataFrame中的每一行都是不同的快餐店):

import pandas as pd
import geopy.distance

df = pd.DataFrame({'Fast Food Place':[1,2,3], 'Lat':[33,34,35], 'Lon':[42,43,44]})

for index1, row1 in df.iterrows():
    num_fastfood = 0

    for index2, row2 in df.iterrows():
        # calculate distance in miles between longitude and latitude
        dist = geopy.distance.vincentydistance(row1[['Lat','Lon']],
                                               row2[['Lat','Lon']]).miles

        # if fast food is within 5 miles, increment num_fastfood
        if dist < 5: # if less than five miles
            num_fastfood = num_fastfood + 1

    df.loc[index1, 'num_fastfood_5miles'] = num_fastfood - 1 # (subtract 1 to exclude self)

但这在非常大的数据集(即50,000行)上非常慢.我考虑过使用KDTree进行搜索,但好奇是否其他人可以使用更快的方法

解决方法:

使用scipy.spatial.cKDTree的实现:

from scipy.spatial import cKDTree

def find_neighbours_within_radius(xy, radius):
    tree = cKDTree(xy)
    within_radius = tree.query_ball_tree(tree, r=radius)
    return within_radius

def flatten_nested_list(nested_list):
    return [item for sublist in nested_list for item in sublist]

def total_neighbours_within_radius(xy, radius):
    neighbours = find_neighbours_within_radius(xy, radius)
    return len(flatten_nested_list(neighbours))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐