此代码使用 Python Pandas 库读取 Excel 文件,并利用 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)

该代码不会报错。

Python Pandas 计算 Excel 文件中经纬度距离代码示例

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

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