python Geopy Geocoders以一种方式返回正确的结果,但不以另一种方式返回

sqougxex  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(189)

我在找几所大学的地址。如果我这么做了,一切都会好起来的。

import pandas as pd
import numpy as np
import pandas as pd
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent='ryan-data')

import pandas as pd

df = ['Rutgers University, New Jersey',
        'Bucknell University, Pennsylvania',
        'Colgate University, New York',
        'Cornell University, New York',
        'Syracuse University, New York']

df = pd.DataFrame(df)
df.columns=['school']
df.head()

df['location'] = df['school'].apply(lambda x: geolocator.geocode(x))
df.head()

当我这样做的时候,一切都很好。但是,如果我从CSV文件中读取完全相同的地址,就像这样。

try:
     df['location'] = df['school'].apply(lambda x: geolocator.geocode(x))
except:
     df['location'] = 'not found'
    
df.head()

完全相同的代码总是抛出错误。我不想把每个地址都打出来。我只想从CSV读取并获得结果。我该怎么做?

sr4lhrrt

sr4lhrrt1#

用这个就行了

import warnings
warnings.filterwarnings('ignore')

import pandas as pd
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter

#Creating an instance of Nominatim Class
geolocator = Nominatim(user_agent="my_request")
 
#applying the rate limiter wrapper
geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
 
# applying the method to pandas DataFrame
try:
    df['Location'] = df['Address'].apply(geocode)
    df['Lat'] = df['Location'].apply(lambda x: x.latitude if x else None)
    df['Lon'] = df['Location'].apply(lambda x: x.longitude if x else None)
except:
    df['Location'] = 'none found'

相关问题