Python 从地址生成 lat/long 点

Python generate lat/long points from address

如何在 python 中获取地址并从中生成经纬度坐标?我有几个地址,我想得到经纬度点,但似乎不起作用。

我用过 geopandas,但 returns 我什么都没有。我也对 user_agent 使用什么感到困惑。这是我的代码,

import pandas as pd
from geopy.geocoders import Nominatim

df2['location_lat'] = ""
df2['location_long'] = ""

geolocator = Nominatim(user_agent="myApp")

for i in df2.index:
    try:
        #tries fetch address from geopy
        location = geolocator.geocode(df2['Location'][i])
        
        #append lat/long to column using dataframe location
        df2.loc[i,'location_lat'] = location.latitude
        df2.loc[i,'location_long'] = location.longitude
  
    except:
        #catches exception for the case where no value is returned
        #appends null value to column
        df2.loc[i,'location_lat'] = ""
        df2.loc[i,'location_long'] = ""
   

感谢任何帮助。谢谢

我没有pandas,但我认为你可以使用它

代码:

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent='your_app_name')

addresses = [
            '20, Willmannstraße, Fechenheim, Ost, Frankfurt am Main, Hessen, 60386, Deutschland',
            '20, Willmannstraße, Fechenheim, Ost, Frankfurt am Main, Hessen, 60386, Deutschland',
            'Pöhlen, Schönberg, Sandesneben-Nusse, Herzogtum Lauenburg, Schleswig-Holstein, 22929, Deutschland',
            'Pöhlen, Schönberg, Sandesneben-Nusse, Herzogtum Lauenburg, Schleswig-Holstein, 22929, Deutschland',
            'Pöhlen, Schönberg, Sandesneben-Nusse, Herzogtum Lauenburg, Schleswig-Holstein, 22929, Deutschland'
]

coordinates = []

for address in addresses:
    location = geolocator.geocode(address)

    lat, lon = location.latitude, location.longitude

    coordinates.append((lat, lon))

print(coordinates)

# output:
[(50.1262402, 8.767057053362574),
 (50.1262402, 8.767057053362574),
 (53.6805214, 10.4282207),
 (53.6805214, 10.4282207),
 (53.6805214, 10.4282207)]

希望对你有帮助=D

您可以直接在 DataFrame 列上使用 apply

import pandas as pd
from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="myApp")

df2 = pd.DataFrame({'Location':
            ['2094 Valentine Avenue,Bronx,NY,10457',
             '1123 East Tremont Avenue,Bronx,NY,10460',
             '412 Macon Street,Brooklyn,NY,11233']})

df2[['location_lat', 'location_long']] = df2['Location'].apply(
    geolocator.geocode).apply(lambda x: pd.Series(
        [x.latitude, x.longitude], index=['location_lat', 'location_long']))

它应该给出:

                                  Location  location_lat  location_long
0     2094 Valentine Avenue,Bronx,NY,10457     40.852905     -73.899665
1  1123 East Tremont Avenue,Bronx,NY,10460     40.840130     -73.876245
2       412 Macon Street,Brooklyn,NY,11233     40.682651     -73.934353