python - 当我没有收到手动运行代码时,在 Python for 循环中收到 KeyError
问题描述
我正在尝试使用 geopy 库来获取旧金山 10 个社区的纬度和经度值。出于某种原因,代码将单独运行索引每个邻域,但是当我尝试循环遍历整个列时会返回 KeyError。
例如,以下代码返回第一个社区的坐标,即加利福尼亚州旧金山的金银岛:
geolocator = Nominatim(user_agent = 'sf_explorer')
location = geolocator.geocode(cheap_df['Address'][0])
latitude = location.latitude
longitude = location.longitude
print('The geographical coordinates of Treasure Island, San Francisco are {}, {}.'.format(latitude, longitude))
我想在整个列中循环这段代码,并将纬度和经度值附加到两个单独的列表中。以下是我如何调整代码以作为 for 循环运行:
lat = []
lon = []
for i in cheap_df['Address']:
geolocator = Nominatim(user_agent = 'sf_explorer')
location = geolocator.geocode(cheap_df['Address'][i])
latitude = location.latitude
longitude = location.longitude
lat.append(latitude)
lon.append(longitude)
但是,在运行此命令时,我得到以下 KeyError,箭头指向第 7 行(以位置开头的行):
KeyError: 'Treasure Island, San Francisco, California'
有谁知道我做错了什么,以及如何解决?任何帮助是极大的赞赏!
解决方案
i
是 的元素cheap_df['Address']
,而不是索引。您不应该尝试将其用作索引,而是按原样使用它。
location = geolocator.geocode(i)
推荐阅读
- neural-network - Pytorch Forward Pass 每次都改变?
- jhipster - JHipster Generator v4.14 未显示 React 选项
- java - 如何在netbeans上的spring应用程序中放置css和js?
- javascript - 为什么`XMLHttpRequest.prototype.onload`抛出Uncaught TypeError:非法调用
- java - 如何从 Firestore 获取数组?
- c++ - 在类中重载 >> 运算符
- json - 使用反射在 Go 中创建地图
- sql - SQL从同一个对象中选择不同的值
- python - Pandas 将行与具有相似部分多索引的行进行比较
- javascript - ExtJS:全局函数在页面加载之前执行。怎么拖延?