欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > Python_计算两个省市之间的直线距离

Python_计算两个省市之间的直线距离

2025/11/19 15:02:59 来源:https://blog.csdn.net/Jay_NanX/article/details/145325504  浏览:    关键词:Python_计算两个省市之间的直线距离

存在如下表格:

发货省发货市到货省到货市
浙江杭州河南郑州
import pandas as pd
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
from tqdm import tqdm# 初始化地理编码器
geolocator = Nominatim(user_agent="geo_distance_calculator", timeout=10)# 缓存字典
coordinate_cache = {}# 获取省市的经纬度
def get_coordinates(province, city):key = f"{province}-{city}"if key in coordinate_cache:return coordinate_cache[key]try:location = geolocator.geocode(f"{province} {city}")if location:coord = (location.latitude, location.longitude)coordinate_cache[key] = coordreturn coordelse:return Noneexcept Exception as e:print(f"Error geocoding {province} {city}: {e}")return None# 计算两点之间的直线距离
def calculate_distance(coord1, coord2):if coord1 and coord2:return geodesic(coord1, coord2).kilometerselse:return None# 读取 Excel 文件
input_file = "free.xlsx"  # 替换为你的文件名
output_file = "free_output.xlsx"
df = pd.read_excel(input_file)# 添加进度条
tqdm.pandas()# 添加新的列用于保存距离
df["发货坐标"] = df.progress_apply(lambda row: get_coordinates(row["发货省"], row["发货市"]), axis=1)
df["到货坐标"] = df.progress_apply(lambda row: get_coordinates(row["到货省"], row["到货市"]), axis=1)
df["直线距离 (公里)"] = df.progress_apply(lambda row: calculate_distance(row["发货坐标"], row["到货坐标"]), axis=1)# 保存到新的 Excel 文件
df.to_excel(output_file, index=False)
print(f"处理完成,结果已保存到 {output_file}")

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com