This Python code calculates the distance between two points using their latitude and longitude values. It reads an Excel file containing these coordinates, processes the data using the Haversine formula, and saves the results in a new Excel file.

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 Haversine Formula: Calculate Distance Between Latitude and Longitude Points

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

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