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

如何根据Excel中的城市和国家获取经纬度?代码返回None求解

问题诊断与修复方案

你的代码全量返回None,核心问题集中在以下几点,逐一修复即可解决:

1. 变量名拼写错误

代码初始化的是gelocator,但循环中调用的是geolocator,变量名不一致导致地理编码对象调用失败,直接返回None。

2. 整列拼接而非逐行拼接

直接使用city + ',' + country是对整个Series做拼接,并非取当前行的城市+国家组合,地理编码无法识别这种批量拼接的字符串。

3. 未处理请求频率限制

Nominatim对请求频率有严格限制,短时间内大量请求会被拒绝,返回None,必须添加请求间隔。


修复后的完整代码

import pandas as pd
from geopy.geocoders import Nominatim
import time

# 修正变量名,使用合规的user-agent
geolocator = Nominatim(user_agent="geo_locator_demo")

df = pd.read_excel("location.xlsx")

# 提前清理地址中的多余空格
df['City'] = df['City'].str.strip()
df['Country'] = df['Country'].str.strip()

longitude = []
latitude = []

for i in df.index:
    # 逐行拼接标准地址格式
    address = f"{df.loc[i, 'City']}, {df.loc[i, 'Country']}"
    try:
        loc = geolocator.geocode(address)
        if loc:
            latitude.append(loc.latitude)
            longitude.append(loc.longitude)
        else:
            latitude.append(None)
            longitude.append(None)
        # 添加1秒延时,规避请求限制
        time.sleep(1)
    except Exception as e:
        print(f"第{i}行解析失败: {e}")
        latitude.append(None)
        longitude.append(None)
        time.sleep(2)

df["Longitude"] = longitude
df["Latitude"] = latitude

print(df)

额外优化建议

  • 数据预处理:提前清理Excel中城市、国家名称的拼写错误、多余空格,避免无效请求。
  • 批量处理工具:如果数据量较大,建议使用geopy.extra.rate_limiter.RateLimiter自动控制请求间隔,比手动sleep更稳定。
  • 日志记录:可以将解析失败的地址写入日志文件,方便后续排查修正。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:55:26