使用 Nominatim geopy 进行反向地理编码时处理丢失数据的错误

问题描述

我正在尝试从 geopy 反向地理编码中提取地址的各个部分。

我有一个包含纬度和经度值的数据框。

我能够提取国家/地区(如下面的代码所示),因为所有行都包含该信息,但是当我想提取城市或道路等其他元素时,某些行没有此类信息,程序会抛出一个错误。

如何处理错误异常,只在数据缺失的地方收到NaN或0?

import geopy
import pandas as pd


def get_country(df,locator,latitude,longitude):
    location = locator.reverse((df[latitude],df[longitude]))
    return location.raw['address']['country']


locator = geopy.Nominatim(user_agent='my-application')

df = pd.DataFrame({
    'latitude': [42.66113281,42.66281128,42.64385986,42.64657593,42.6476291,42.6656645,42.65878296,42.64697266,42.64666748],'longitude': [21.16506121,21.16527831,21.21033445,21.17226068,21.18473427,21.1519355,21.17131968,21.1841433,21.172197]
})
countries = df.apply(get_country,axis=1,locator=locator,latitude='latitude',longitude='longitude')

当我只想获取这个 KeyError 显示的城市时

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-293-feadf6731600> in <module>()
     14     'longitude': [21.16506121,21.172197]
     15 })
---> 16 countries = df.apply(get_country,longitude='longitude')

5 frames
<ipython-input-293-feadf6731600> in get_country(df,longitude)
      5 def get_country(df,longitude):
      6     location = locator.reverse((df[latitude],df[longitude]))
----> 7     return location.raw['address']['city']
      8 
      9 

KeyError: 'city'

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...