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

遍历Pandas DataFrame获取马里兰州城市经纬度遇重复值问题

解决你的经纬度重复问题

嘿,我一眼就瞅出你代码里的问题啦,这才导致所有城市的经纬度全是重复值!

问题根源拆解

1. 列表被单个值直接覆盖

你一开始明明定义了latitude=[]和longitude=[]空列表,但循环里却用latitude = location.latitude把列表直接替换成了单个数值!每次循环都会把之前的值冲掉,最后循环结束时,这俩变量就只剩最后一个城市的坐标,赋值给DataFrame列自然全是重复的。

2. 没必要每次循环都初始化Geolocator

每次循环都geolocator = Nominatim(user_agent="tor_explorer")属于重复创建实例,既浪费资源还可能触发服务的请求限制,完全可以把这行移到循环外面。

修正后的代码

我给你调整了代码,还加了异常处理(防止有些城市找不到坐标导致程序崩溃):

from geopy.geocoders import Nominatim
import pandas as pd

# 假设你的df已经完成初始化(比如从文件读取)
# df = pd.read_csv("你的数据文件.csv")

# 只创建一次Geolocator实例,放在循环外面
geolocator = Nominatim(user_agent="tor_explorer")
latitude = []
longitude = []

for city in df["City"]:
    address = city + ', MD'
    try:
        location = geolocator.geocode(address)
        if location:
            # 用append把坐标添加到列表里,而不是覆盖列表
            latitude.append(location.latitude)
            longitude.append(location.longitude)
        else:
            # 找不到坐标时填充空值,避免数据错位
            latitude.append(None)
            longitude.append(None)
    except Exception as e:
        print(f"获取{city}坐标时出错: {e}")
        latitude.append(None)
        longitude.append(None)

# 把完整的坐标列表赋值给DataFrame新列
df['latitude'] = latitude
df['longitude'] = longitude

关键改动说明

  • 把geolocator初始化移到循环外,减少不必要的资源消耗
  • 用append()方法累积每个城市的坐标,不再覆盖列表
  • 增加异常处理和空值判断,避免因单个城市找不到坐标导致整个程序中断

这样运行后,每个城市的经纬度就会对应到DataFrame的每一行啦!

内容的提问来源于stack exchange,提问作者Liz M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:17:50