首页 > 解决方案 > 当我没有收到手动运行代码时,在 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'

有谁知道我做错了什么,以及如何解决?任何帮助是极大的赞赏!

标签: pythonfor-loopgeolocationgeopy

解决方案


i是 的元素cheap_df['Address'],而不是索引。您不应该尝试将其用作索引,而是按原样使用它。

location = geolocator.geocode(i)

推荐阅读