我想将纬度和经度转换为具有大数据集的城市。
我使用的代码如下:
import numpy as np
import geopy
import time
def get_city_with_retry(df, geolocator, lat_field, lon_field, retries=3, delay=1):
for _ in range(retries):
try:
location = geolocator.reverse((df[lat_field], df[lon_field]), exactly_one=True)
return location.raw['address'].get('city', location.raw['address'].get('town', 'Unknown'))
except Exception as e:
print(f"Error occurred for coordinates ({df[lat_field]}, {df[lon_field]}): {e}")
time.sleep(delay)
return 'Unknown'
# Initialize geolocator
geolocator = geopy.Nominatim(user_agent='my-geocoding-app/1.0')
# Apply the function with retry logic
transactions_data['City'] = transactions_data.apply(lambda row: get_city_with_retry(row, geolocator, 'Latitude', 'Longitude'), axis=1)
# Display the result
print(transactions_data)
但是有错误,比如:
警告:urllib3.connectionpool:在连接因“NewConnectionError(”
引起:无法建立新连接:[错误111]连接被拒绝')': /reverse?lat=-7.964164&lon=112.623673&format=json&addressdetails=1 警告:urllib3.connectionpool:在连接因“NewConnectionError(” :无法建立新连接:[Errno] 111]连接被拒绝')': /reverse?lat=-7.964164&lon=112.623673&format=json&addressdetails=1 坐标(-7.964164,112.623673)发生错误:HTTPSConnectionPool(host ='nominatim.openstreetmap.org',port = 443):网址超出最大重试次数:/reverse?lat = -7.964164&lon = 112.623673&format = json&addressdetails = 1(由 ConnectTimeoutError( , '与 nominatim.openstreetmap.org 的连接超时。(连接超时=1)'))
代码的另一种解决方案是什么?
从您提供的错误来看,这看起来像是超时问题。尝试在初始化地理定位器时设置超时参数,如下所示-
geolocator = geopy.Nominatim(user_agent='my-geocoding-app/1.0', timeout=10)