【发布时间】:2018-02-09 08:45:00
【问题描述】:
我有两个独立的数据集,df 和 df2,每个数据集都有 longitude 和 latitude 列。我要做的是在df 中找到最接近df2 中的点,并在km 中计算它们之间的距离,并将每个值附加到df2 中的新列中。
我想出了一个解决方案,但请记住,df 有 +700,000 行,df2 有大约 60,000 行,所以我的解决方案需要很长时间才能计算出来。我能想出的唯一解决方案是使用双 for 循环...
def compute_shortest_dist(df, df2):
# array to store all closest distances
shortest_dist = []
# radius of earth (used for calculation)
R = 6373.0
for i in df2.index:
# keeps track of current minimum distance
min_dist = -1
# latitude and longitude from df2
lat1 = df2.ix[i]['Latitude']
lon1 = df2.ix[i]['Longitude']
for j in df.index:
# the following is just the calculation necessary
# to calculate the distance between each point in km
lat2 = df.ix[j]['Latitude']
lon2 = df.ix[j]['Longitude']
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
# store new shortest distance
if min_dist == -1 or distance > min_dist:
min_dist = distance
# append shortest distance to array
shortest_dist.append(min_dist)
这个函数的计算时间太长,我知道必须有更有效的方法,但我不太擅长pandas 语法。
感谢您的帮助。
【问题讨论】:
-
它必须循环 420 亿次,所以我认为没有真正有效的计算方法。您可以尝试使用一个模块来并行化该过程,使其速度提高两倍、四倍,但我想不出更好的方法
-
numpy.ndarray的计算应该比pandas.core.series.Series的计算快。您可以在提取经纬度时尝试添加.values。
标签: python pandas math multiple-columns latitude-longitude