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.
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