首页 > 解决方案 > Geopy reverse 返回“city”、“district”和“borough”的键错误,尽管它位于 JSON 响应对象中

问题描述

我正在尝试运行一个非常简单的 geopy 反向脚本,该脚本采用经纬度坐标并专门返回国家、州和城市。所有这三个都可以轻松地从 JSON 响应对象中提取。但是,当我尝试提取“城市”特征时,我得到一个 KeyError。如果我仔细检查“城市”是否在响应对象中,它肯定是(见下文),那么到底发生了什么?我可以毫无问题地提取国家和州,为什么不能提取城市?我也注意到地区和自治市镇发生了这种情况。

这是我的代码:

df = pd.read_csv('data.csv')
geolocator = Nominatim(user_agent='latlongconvert')
df['address'] = df['LastMatchingLatLong'].apply(geolocator.reverse)

df['country'] = df['address'].apply(lambda x: (x.raw['address']['country']))
df['state'] = df['address'].apply(lambda x: (x.raw['address']['state']))
df['city'] = df['address'].apply(lambda x: (x.raw['address']['city']))

最后一行会产生以下错误:KeyError: 'city'

当我查看特定行时,它清楚地包含城市键:

df['address'][0].raw['address']

Ouput:
{'tourism': 'Schwanentempel',
 'road': 'Auedamm',
 'suburb': 'Südstadt',
 'city': 'Kassel',
 'municipality': 'Niestetal',
 'state': 'Hessen',
 'postcode': '34121',
 'country': 'Deutschland',
 'country_code': 'de'}

我什至可以用df['address'][0].raw['address']['city']它来为那个特定的行提取它。

标签: pythonpandaskeyerrorgeopy

解决方案


对于遇到此问题的其他人,Geopy 并不总是返回城市、自治市镇、地区等,因此使用 lambda 函数而不考虑缺失值会给您一个 keyerror。

以下代码为我解决了这个问题:

df['country'] = df['address'].apply(lambda x: (x.raw['address']['country']))
df['state'] = df['address'].apply(lambda x: (x.raw['address']['state']))
df['city'] = df['address'].apply(lambda x: (x.raw['address']['city'] if 'city' in x.raw['address'].keys() else None ))

推荐阅读