python - 通过 geopy 从 pandas 数据框中获取所有 long 和 lat
问题描述
我有一个包含位置数据的数据框,例如“加利福尼亚州洛杉矶”。
目标是遍历列的所有条目,并将 long 和 lat 保存在新列中。非常欢迎任何输入或提示!
我尝试了单个值并且它有效。
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="xxx")
location=geolocator.geocode(df['Location'][1])
print(location.longitude)
print(location.latitude)
-117.8704931
33.7500378
现在,作为一个初学者,我想让我们做一个 for 循环:
df['lat']=0
print(df['Location'][1])
for x in range(1,len(df)+1):
location = geolocator.geocode(df['Location'][x])
df['loc'][x]=location.latitude
我收到以下警告:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
df['loc'][x]=location.latitude
约2分钟后出现以下错误:
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\skpok\Anaconda3\lib\site-packages\geopy\geocoders\base.py", line 344, in _call_geocoder
page = requester(req, timeout=timeout, **kwargs)
File "C:\Users\skpok\Anaconda3\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "C:\Users\skpok\Anaconda3\lib\urllib\request.py", line 543, in _open
'_open', req)
File "C:\Users\skpok\Anaconda3\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Users\skpok\Anaconda3\lib\urllib\request.py", line 1360, in https_open
context=self._context, check_hostname=self._check_hostname)
File "C:\Users\skpok\Anaconda3\lib\urllib\request.py", line 1319, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error timed out>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\skpok\Downloads\test123.py", line 12, in <module>
location = geolocator.geocode(df['Location'][x])
File "C:\Users\skpok\Anaconda3\lib\site-packages\geopy\geocoders\osm.py", line 309, in geocode
self._call_geocoder(url, timeout=timeout), exactly_one
File "C:\Users\skpok\Anaconda3\lib\site-packages\geopy\geocoders\base.py", line 367, in _call_geocoder
raise GeocoderTimedOut('Service timed out')
geopy.exc.GeocoderTimedOut: Service timed out
解决方案
Nominatim 具有每秒最大请求规则(每秒 1 个)。您应该尝试在脚本在循环之间休眠的子句中添加一个子句。
你可以试试
import time
df['lat']=0
print(df['Location'][1])
for x in range(1,len(df)+1):
location = geolocator.geocode(df['Location'][x])
time.sleep(2)
df.at[x, 'lat']=location.latitude
推荐阅读
- html - 如何将链接添加到 CSS 选择字段?
- python - 如何使用硒(Python)从 SELECT 中选择一个选项?
- flask-mongoengine - 如何使用 flask-mongoengine 连接 cosmosDB
- pytorch - 简单的卷积网络
- javascript - 如何从适用于每个选择的多项选择中获取值?
- javascript - 为什么嵌套的 postMessage 会导致 rAF 在 setTimeout 之前被触发?
- android-studio - 颤振设备选择未显示(目标选择器)
- c# - 为什么使用 CellPainting 方法向 datagridview 单元格添加彩色矩形会使单元格中的文本看起来模糊?
- java - ssl_client:raw.githubusercontent.com:证书验证失败:自签名证书在
- android - 如何像 WhatsApp 一样在 PIP 模式下播放 YouTube 视频?