1

So I have a dataframe with two columns cities and counties that has some cities from Maryland USA. I am trying to loop through to get the latitude and longitude coordinates for each city using the following code:

from geopy.geocoders import Nominatim
latitude=[]
longitude=[]
for city in df["City"]:

    address = city + ', MD'

    geolocator = Nominatim(user_agent="tor_explorer")
    location = geolocator.geocode(address)
    latitude = location.latitude
    longitude = location.longitude
df['latitude']=latitude
df['longitude']=longitude

But when I print latitude or longitude there's only one value in the list so when I put it into the dataframe it just repeats the same latitude and longitude for every city.

Liz M.
  • 25
  • 3
  • It's because you're setting `df['latitude'] = latitude` and `df['longitude'] = longitude` outside of the loop, which sets those values in every single row. You need to set those values within the loop for that specific city. – snailor Jun 29 '20 at 13:33
  • geopy docs have a section dedicated to working with pandas, see https://geopy.readthedocs.io/en/stable/#usage-with-pandas – KostyaEsmukov Jul 04 '20 at 17:46

1 Answers1

1

You are assigning the last value the for loop takes, so try to append each value of the for loop:

latitude=[]
longitude=[]
for city in df["City"]:

    address = city + ', MD'

    geolocator = Nominatim(user_agent="tor_explorer")
    location = geolocator.geocode(address)
    latitude.append(location.latitude)
    longitude.append(location.longitude)
df['latitude']=latitude
df['longitude']=longitude
MrNobody33
  • 6,413
  • 7
  • 19