from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="My App")
#tries fetch address from geopy
location = geolocator.geocode(df2['address'])
#append lat/long to column using dataframe location
df2.loc['lat'] = location.latitude
df2.loc['long'] = location.longitude
#catches exception for the case where no value is returned
#appends null value to column
df2.loc['lat'] = ""
df2.loc['long'] = ""
df2.head()
Here is the code that I tried using ^^^
geolocator = Nominatim(user_agent="My App")
location = geolocator.geocode("33000 N KINGSHIGHWAY BLVD, St.Louis" )
print((location.latitude, location.longitude))
This Code above worked when I picked only one address. But ofc I want it to run without me giving it a specific address.
CodePudding user response:
def get_lat_long(address):
try:
x = geolocator.geocode(address)
return x.latitude, x.longitude
except:
return np.nan, np.nan
df[['latitude', 'longitude']] = df.apply(lambda x: get_lat_long(x.address), axis=1, result_type='expand')
print(df)
Output:
address latitude longitude
0 33000 N KINGSHIGHWAY BLVD, St.Louis 38.649933 -90.263803
CodePudding user response:
This is untested, because I don't want to install the package, but this is the kind of thing you need:
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="My App")
lat, lon = [], []
for addr in df2['address'].tolist():
location = geolocator.geocode(addr)
lat.append( location.latitude )
lon.append( location.longitude )
df2['latitude'] = np.array(lat)
df2['longitude'] = np.array(lon)
Or:
locs = [geolocator.geocode(addr) for addr in df2['address'].tolist()]
locs = np.array(locs)
df2['latitide'] = locs[:,0]
df2['longitude'] = locs[:,1]