这段代码实现了读取一个 Excel 文件并计算每个点之间的距离,最后将结果保存为新的 Excel 文件。其中,使用了 pandas 库来读取和保存 Excel 文件,使用了 math 库中的函数来计算距离,其中采用了 Haversine 公式来计算地球上两点之间的距离。具体实现过程是:

import pandas as pd
from math import radians, sin, cos, sqrt, atan2

# 读取excel文件
data = pd.read_excel('D:\课件\毕设\数据处理\根据经纬度计算距离\1.xlsx')

# 计算每个点之间的距离
def calculate_distance(row):
    # 将经纬度转换为弧度
    lat1, lon1, lat2, lon2 = map(radians, [row['o_lat'], row['o_lon'], row['d_lat'], row['d_lon']])
    # Haversine公式计算距离
    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 = 6371 * c * 1000  # 将距离转换为单位为米
    return distance

# 将计算结果保存在第六列
data['distance'] = data.apply(calculate_distance, axis=1)

# 将结果保存为新的excel文件
data.to_excel('result.xlsx', index=False)

读取 Excel 文件并将经纬度转换为弧度,然后使用 Haversine 公式计算距离,最后将距离保存在新的 Excel 文件中。

Python 使用 Haversine 公式计算 Excel 数据点间距离

原文地址: https://www.cveoy.top/t/topic/m1mX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录