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

通过DataFrame经纬度列获取地址遇报错:解决reverse()函数ValueError问题

解决geopy.reverse()报错ValueError: Must be a coordinate pair or Point的问题

问题描述

我有一个包含Store_latitude(纬度)和Store_longitude(经度)列的DataFrame,调用geolocator.reverse()获取地址时触发报错ValueError: Must be a coordinate pair or Point。尝试用list(zip(zips['Store_latitude'], zips['Store_longitude']))生成元组列传入,仍出现相同错误。

原代码

import pandas as pd
from geopy.geocoders import Nominatim
from decimal import Decimal
from geopy.point import Point

zips = pd.read_excel("zips.xlsx")
geolocator = Nominatim(user_agent="geoapiExercises")

zips['Store_latitude']= zips['Store_latitude'].astype(str)
zips['Store_longitude'] = zips['Store_longitude'].astype(str)
zips['Location'] = list(zip(zips['Store_latitude'], zips['Store_longitude']))
zips['Address'] = geolocator.reverse(zips['Location'])

DataFrame示例

Store_latitudeStore_longitude
34.2262225-118.4508349
34.017667-118.149135

解决方案

错误原因分析

  1. 经纬度被转为字符串:geopy的reverse()需要数值类型(float/Decimal)的坐标对,字符串无法被识别为合法坐标。
  2. 直接传入Series:reverse()一次只能处理单个坐标,不能直接传入整个Series对象。

修正后的代码

import pandas as pd
from geopy.geocoders import Nominatim
from geopy.point import Point

zips = pd.read_excel("zips.xlsx")
geolocator = Nominatim(user_agent="geoapiExercises")

# 确保经纬度为数值类型(若读取后不是则转换)
zips['Store_latitude'] = zips['Store_latitude'].astype(float)
zips['Store_longitude'] = zips['Store_longitude'].astype(float)

# 逐行处理坐标获取地址
def get_address(row):
    try:
        # 用Point包装坐标,或直接传元组(row['Store_latitude'], row['Store_longitude'])
        location = geolocator.reverse(Point(row['Store_latitude'], row['Store_longitude']))
        return location.address if location else None
    except Exception as e:
        print(f"处理坐标({row['Store_latitude']}, {row['Store_longitude']})时出错: {e}")
        return None

zips['Address'] = zips.apply(get_address, axis=1)

关键修改点

  • 移除经纬度转字符串的操作,保留float类型,确保geopy能识别坐标对。
  • 使用apply逐行调用reverse(),适配方法的单坐标处理特性。
  • 增加异常捕获,避免单个坐标处理失败导致程序中断,同时输出错误信息便于排查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:45:25