I'm trying to use the geopy library to get the latitude and longitude values for 10 neighborhoods in San Francisco. For some reason, the code will run individually indexing each neighborhood, but returns a KeyError when I try to loop it through the whole column.
For example, the following code returns the coordinates for the first neighborhood, which is Treasure Island, San Francisco, California:
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))
I want to loop this code through the entirety of the column and append the latitude and longitude values to two separate lists. Here is how I adapted the code to run as a for loop:
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)
However, upon running this I get the following KeyError with the arrow pointing at line 7 (the line that starts with location):
KeyError: 'Treasure Island, San Francisco, California'
Does anyone know what I'm doing wrong, and how I can fix it? Any help is greatly appreciated!
i
is an element of cheap_df['Address']
, not an index. You shouldn't try to use it as the index, just use it as it is.
location = geolocator.geocode(i)