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

如何清理Pandas DataFrame中location列的冗余信息与坐标?

解决方法:替换Location对象为原始区名

嘿,这个问题很常见——你现在存到location列的是Nominatim返回的完整Location对象,它包含了地址解析后的所有信息(比如完整地址、坐标甚至额外元数据),所以才会出现冗余内容。要只保留原始区名,有两种简单的处理方式:

方式1:在数据收集阶段直接存入区名

修改你循环里的append语句,把location换成原始的borough变量就行,这样生成的DataFrame一开始就带正确的区名。另外建议把geolocator实例化移到循环外,避免重复创建实例浪费资源:

import pandas as pd
from geopy.geocoders import Nominatim

dfB = []
city = 'Toronto, Canada'
boroughs = df["Boroughs"]
geolocator = Nominatim(user_agent="foursquare_agent")  # 移到循环外更高效

for borough in boroughs:
    try:
        address = borough + ', ' + city
        location = geolocator.geocode(address)
        lat = location.latitude
        lng = location.longitude
        dfB.append([borough, lat, lng])  # 这里把location换成原始区名borough
    except Exception as e:
        print(f"获取{address}坐标失败: {str(e)}")  # 优化错误提示,方便排查问题

dfB = pd.DataFrame(dfB, columns=["location", "lat", "lng"])
dfB

方式2:如果已经生成了dfB,事后替换location列

如果你已经跑完了原来的代码,不想重新爬取坐标,可以直接用原始的boroughs序列覆盖location列:

dfB['location'] = boroughs.values

这样就能得到你预期的结果:location列仅保留对应区名,同时保留正确的经纬度数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:03:29