python - 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']
它来为那个特定的行提取它。
解决方案
对于遇到此问题的其他人,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 ))
推荐阅读
- node.js - 如何使用 node.js 在标头中传递 JWT 令牌来执行 GET 请求
- ios - 在iOS swift中将图像上传到服务器
- python - 张量流分类尝试中的损失没有减少
- shiny - Shiny 中的用户定义函数输出不在范围内
- flutter - 找不到正确的提供者
在这个 RestoreLocalBackupPage 小部件之上,如何以比我做的更简单的方式解决这个问题? - excel - Excel:将excel中的动态数组函数UNIQUE应用于行和列> 1的表
- r - 用几行代码运行 n 次线性回归并将结果存储在矩阵中
- gitlab - 带有生产和测试环境的 GitLab 分支
- python - 如何使用 CMake 查找 Python 解释器和库的最低版本
- javascript - Highcharts 可变半径饼图-外圆