当前位置:首页 > Python > 正文

Python经纬度格式化方法教程 - 度分秒与十进制坐标转换指南

Python经纬度格式化方法

学习如何在度分秒和十进制格式之间转换地理坐标

为什么需要格式化经纬度?

地理坐标通常以两种格式表示:

  • 十进制格式:如 40.7128°N, -74.0060°W(简洁,适合计算)
  • 度分秒格式:如 40°42'46.08"N, 74°0'21.6"W(传统格式,可读性高)

在GIS系统、地图服务和位置应用中,需要在两种格式间转换。Python提供了高效的方法来处理这些转换。

十进制转度分秒

将十进制坐标转换为度分秒格式:

def decimal_to_dms(decimal_deg, coord_type):
    # 确定方向(东/西/南/北)
    direction = ""
    if coord_type == "latitude":
        direction = "N" if decimal_deg >= 0 else "S"
    elif coord_type == "longitude":
        direction = "E" if decimal_deg >= 0 else "W"
    
    # 确保度数为正
    decimal_deg = abs(decimal_deg)
    
    # 计算度、分、秒
    degrees = int(decimal_deg)
    minutes_float = (decimal_deg - degrees) * 60
    minutes = int(minutes_float)
    seconds = round((minutes_float - minutes) * 60, 2)
    
    # 返回格式化字符串
    return f"{degrees}°{minutes}'{seconds}\"{direction}"

# 示例使用
lat = 40.7128
lon = -74.0060
print("纬度:", decimal_to_dms(lat, "latitude"))  # 40°42'46.08"N
print("经度:", decimal_to_dms(lon, "longitude")) # 74°0'21.6"W

输入

十进制坐标:

纬度: 40.7128

经度: -74.0060

输出

度分秒格式:

纬度: 40°42'46.08"N

经度: 74°0'21.6"W

度分秒转十进制

将度分秒格式转换为十进制坐标:

def dms_to_decimal(dms_str):
    # 分割字符串提取各部分
    parts = dms_str.replace('°', ' ').replace('\'', ' ').replace('"', ' ').split()
    
    # 提取度、分、秒和方向
    degrees = float(parts[0])
    minutes = float(parts[1])
    seconds = float(parts[2])
    direction = parts[3]
    
    # 计算十进制值
    decimal_deg = degrees + minutes/60 + seconds/3600
    
    # 根据方向确定正负
    if direction in ['S', 'W']:
        decimal_deg *= -1
    
    return round(decimal_deg, 6)

# 示例使用
lat_dms = "40°42'46.08\"N"
lon_dms = "74°0'21.6\"W"
print("纬度:", dms_to_decimal(lat_dms))  # 40.7128
print("经度:", dms_to_decimal(lon_dms)) # -74.0060

输入

度分秒坐标:

纬度: 40°42'46.08"N

经度: 74°0'21.6"W

输出

十进制格式:

纬度: 40.7128

经度: -74.0060

高级应用:批量处理坐标

使用Pandas处理CSV文件中的坐标数据:

import pandas as pd

# 创建示例数据
data = {
    'Location': ['New York', 'London', 'Tokyo', 'Sydney'],
    'Latitude': [40.7128, 51.5074, 35.6762, -33.8688],
    'Longitude': [-74.0060, -0.1278, 139.6503, 151.2093]
}
df = pd.DataFrame(data)

# 添加度分秒列
df['Lat DMS'] = df['Latitude'].apply(lambda x: decimal_to_dms(x, "latitude"))
df['Lon DMS'] = df['Longitude'].apply(lambda x: decimal_to_dms(x, "longitude"))

print(df)
Location Latitude Longitude Lat DMS Lon DMS
New York 40.7128 -74.0060 40°42'46.08"N 74°0'21.6"W
London 51.5074 -0.1278 51°30'26.64"N 0°7'40.08"W
Tokyo 35.6762 139.6503 35°40'34.32"N 139°39'1.08"E
Sydney -33.8688 151.2093 33°52'7.68"S 151°12'33.48"E

最佳实践提示

  • 统一格式:项目中保持坐标格式一致
  • 精度处理:根据应用场景确定合适的小数位数(导航需要6位,城市定位需要4位)
  • 验证坐标:确保纬度在-90到90之间,经度在-180到180之间
  • 考虑时区:处理国际数据时注意UTC偏移

本教程介绍了Python中处理地理坐标的基本方法,帮助您在项目中高效转换经纬度格式

实际应用中请根据具体需求调整精度和异常处理

发表评论