You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何批量经纬度逆地理编码获取城市、州、国家信息

批量逆地理编码实现方案

可用修改后代码

以下代码新增了异常捕获、请求限速、批量遍历逻辑,可直接运行实现全量数据查询和导出:

import csv 
import pandas as pd
import numpy as np
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter

input_file = "Lat-Log.csv" 
output_file = "output.csv"
df = pd.read_csv(input_file) 

# 初始化地理编码器,设置10秒超时避免网络波动报错
geolocator = Nominatim(user_agent="geoapiExercises", timeout=10)
# 配置请求限速,每秒最多1次请求,符合Nominatim公开接口的使用规则
reverse_geocode = RateLimiter(geolocator.reverse, min_delay_seconds=1, return_value_on_exception=None)

def city_state_country(row):
    coord = f"{row['Latitude']}, {row['Longitude']}"
    try:
        location = reverse_geocode(coord, exactly_one=True)
        if not location:
            return pd.Series(['', '', ''])
        address = location.raw['address']
        # 兼容不同行政区划等级,无city字段时优先取城镇、乡村名称
        city = address.get('city', address.get('town', address.get('village', '')))
        state = address.get('state', '')
        country = address.get('country', '')
        return pd.Series([city, state, country])
    except:
        # 所有异常场景返回空值,不中断程序运行
        return pd.Series(['', '', ''])

# 批量遍历所有行,将返回结果拆分存入三个新列
df[['City', 'State', 'Country']] = df.apply(city_state_country, axis=1)

# 导出最终结果到CSV,不保存索引列
df.to_csv(output_file, index=False)

大数据量优化方案

针对50万条的大体积数据,可采用以下方案大幅提升查询效率:

  • 去重查询:先提取所有唯一的经纬度组合完成查询,再将结果映射回原数据集,避免重复坐标重复请求,代码示例如下:
# 提取所有唯一经纬度
unique_coords = df[['Latitude', 'Longitude']].drop_duplicates().reset_index(drop=True)
# 仅对唯一坐标发起查询
unique_coords[['City', 'State', 'Country']] = unique_coords.apply(city_state_country, axis=1)
# 将查询结果合并回原数据集
df = df.merge(unique_coords, on=['Latitude', 'Longitude'], how='left')
  • 替换服务源:公开Nominatim接口限速为每秒1次,50万条全量查询预计需要6天左右,如有条件可本地部署Nominatim服务,将domain参数修改为本地服务地址即可解除请求限制。
  • 增量保存:可新增逻辑每处理1000条就保存一次临时文件,避免程序意外退出导致进度丢失。

可选功能:州全称转缩写

如果需要和示例一样输出州缩写(如IL替代Illinois),可新增美国州缩写映射字典,在函数返回前对state字段做替换即可。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 19:54:02