【问题标题】:Calculating coordinate distances with geopy in a pandas data frame在熊猫数据框中使用 geopy 计算坐标距离
【发布时间】:2020-11-03 13:19:44
【问题描述】:
我有下面的代码,用于计算之间的距离
开始乘坐公共交通工具的城市坐标
以及行程结束并返回的城市坐标
价值。特定城市有独特数量的组合
对于一个特定的城市,问题是我有一个庞大的数据集
大约 120 万条记录,并且代码相当慢,因为它
对每个组合进行迭代。我怎样才能重新排列循环所以它
计算唯一的坐标之间的距离
组合并将其应用于重复的组合?是
有什么方法可以减少处理时间?
df_distance = []
for row in clean_df.iterrows():
try:
coords_1 = (row[1].Lat_x, row[1].Lng_x)
coords_2 = (row[1].Lat_y, row[1].Lng_y)
distance = geodesic(coords_1, coords_2).km
df_distance.append(distance)
#print(geodesic(coords_1, coords_2).km)
except ValueError as e:
print(row)
【问题讨论】:
标签:
python-3.x
pandas
coordinates
geopy
【解决方案1】:
我重写了缩短数据集处理时间的循环
坐标距离计算:
我创建了一个空字典,它将保存起点-目的地旅行的独特组合的距离计算。对于唯一的组合,创建一个唯一的代码,它将以字符串形式汇总始发地和目的地城市的代码,并将它们添加到字典中。如果再次遇到(重复)这样的唯一代码,则将距离添加到字典中,否则计算距离并将其添加到字典中。
distance_dict = {}
df_distance = list()
for row in clean_df.iterrows():
try:
uniquecode = str(row[1].from_municipality_code) + str(row[1].to_municipality_code)
if uniquecode in distance_dict:
df_distance.append(distance_dict[uniquecode])
continue
else:
coords_1 = (row[1].Lat_x, row[1].Lng_x)
coords_2 = (row[1].Lat_y, row[1].Lng_y)
distance = geodesic(coords_1, coords_2).km
distance_dict[uniquecode] = distance
df_distance.append(distance)
#print(geodesic(coords_1, coords_2).km)
except ValueError as e:
print(row)