简体   繁体   中英

How do I turn an address into long and lat?(google colab/ Jupyter Notebook)

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

CSV 文件样本

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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM