- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个带有地址列的大型 DataFrame:
data addr
0 0.617964 IN,Krishnagiri,635115
1 0.635428 IN,Chennai,600005
2 0.630125 IN,Karnal,132001
3 0.981282 IN,Jaipur,302021
4 0.715813 IN,Chennai,600005
...
并且我编写了以下函数来将地址替换为地址的经纬度坐标:
from geopy.geocoders import Nominatim
geo_locator = Nominatim(user_agent="MY_APP_ID")
def get_coordinates(addr):
location = geo_locator.geocode(addr)
if location is not None:
return pd.Series({'lat': location.latitude, 'lon': location.longitude})
location = geo_locator.geocode(addr.split(',')[0])
if location is not None:
return pd.Series({'lat': location.latitude, 'lon': location.longitude})
return pd.Series({'lat': -1, 'lon': -1})
然后在地址列上调用 pandas apply 方法,并将结果连接到 DF 的末尾而不是地址列:
df = pd.concat([df, df.addr.apply(get_coordinates)], axis=1).drop(['addr'], axis=1)
但是,由于 get_coordinates 调用第 3 方 API,它失败了:geopy.exc.GeocoderTimedOut:服务超时
如何限制请求以确保在继续下一个值之前得到响应?
更新:
为了进一步改进,我想仅针对唯一值调用 API,即:如果地址 IN,Krishnagiri,635115
在我的 DataFrame 中出现 20 次,我只想调用它一次并应用所有 20 次出现的结果。
更新 2:
日志 + 堆栈跟踪,@Andrew Lavers 代码:
...
Fetched Gandipet, Khanapur, Rangareddy District, Telangana, 500075, India
Fetched Jaipur Municipal Corporation, Jaipur, Rajasthan, 302015, India
Fetched Chennai, Chennai district, Tamil Nadu, India
Exception from geolocator: Fake exception for testing
Backing off for 1 seconds.
Exception from geolocator: Fake exception for testing
Backing off for 3 seconds.
Fetched None
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/geopy/geocoders/base.py", line 344, in _call_geocoder
page = requester(req, timeout=timeout, **kwargs)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open
response = self._open(req, data)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open
'_open', req)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1361, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1321, in do_open
r = h.getresponse()
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1331, in getresponse
response.begin()
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 258, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1002, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 865, in read
return self._sslobj.read(len, buffer)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 625, in read
v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/...//tmp.py", line 89, in <module>
df.addr.apply(get_coordinates)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/series.py", line 3194, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas/_libs/src/inference.pyx", line 1472, in pandas._libs.lib.map_infer
File "/Users/...//tmp.py", line 76, in get_coordinates
location = geo_locator.geocode(addr.split(',')[0])
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/geopy/geocoders/osm.py", line 307, in geocode
self._call_geocoder(url, timeout=timeout), exactly_one
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/geopy/geocoders/base.py", line 371, in _call_geocoder
raise GeocoderTimedOut('Service timed out')
geopy.exc.GeocoderTimedOut: Service timed out
Process finished with exit code 1
最佳答案
这里有一些经过测试的代码可能会有所帮助。 1) 对 Api 指定的简单速率限制(Nominatum 似乎是每秒 1 个,但我成功地低至 0.1 秒)。 2) 字典中的简单结果缓存,可通过测试参数控制 3) 具有乘法减速和线性加速的重试循环。 (减速快,加速慢)4)伪造错误的测试异常
我无法复制您遇到的问题 - 可能是因为您的 API 路径。
一个更健壮的策略可能是构建本地持久缓存并继续重试,直到构建完整的批处理。缓存可以是作为 csv 写入文件的 pandas 数据帧。整体伪代码是这样的。
repeat until all addresses are in the cache
cache = pd.read_csv("cache.csv)
addressess_to_get = addresses in df that are not in cache
for batch of n addresses in addresses_to_get:
cache.add(get_location(addr))
cache.write_csv("cache.csv")
这是测试代码
import datetime
import time
import pandas as pd
from geopy.geocoders import Nominatim
geo_locator = Nominatim(user_agent="notarealemail@gmail.com")
# Define the rate limit function and associated global variable
last_time = datetime.datetime.now()
backoff_time = 0
def rate_limit(min_interval_seconds = .1):
global last_time
sleep = min_interval_seconds - (datetime.datetime.now() - last_time).total_seconds()
if sleep > 0 :
print(f'Sleeping for {sleep} seconds')
time.sleep(sleep)
last_time = datetime.datetime.now()
# make a cache dictionary keyed by address
geo_cache = {}
backoff_seconds = 0
def get_coordinates_with_retry(addr):
# Return coords from global cache if it exists
global backoff_seconds
# set the backoff intital values and factors
max_backoff_seconds = 60
backoff_exponential = 2
backoff_linear = 2
# rate limited API call
rate_limit()
# Retry until max_back_seconds is reached
while backoff_seconds < max_backoff_seconds: # backoff up to this time
if backoff_seconds > 0:
print(f"Backing off for {backoff_seconds} seconds.")
time.sleep(backoff_seconds)
try:
location = geo_locator.geocode(addr)
# REMOVE THIS: fake an error for testing
#import random
#if random.random() < .3:
# raise(Exception("Fake exception for testing"))
# Success - so reduce the backoff linearly
print (f"Fetched {location} for address {addr}")
backoff_seconds = backoff_seconds - backoff_linear if backoff_seconds > backoff_linear else 0
break
except Exception as e:
print(f"Exception from geolocator: {e}")
# Backoff exponentially
backoff_seconds = 1 + backoff_seconds * backoff_exponential
if backoff_seconds > max_backoff_seconds:
raise Exception("Max backoff reached\n")
return(location)
def get_coordinates(addr, useCache = True):
# Return from cache if previously loaded
global geo_cache
if addr in geo_cache:
return geo_cache[addr]
# Attempt using the full address
location = get_coordinates_with_retry(addr)
# Attempt using the first part only if None found
if location is not None:
result = pd.Series({'lat': location.latitude, 'lon': location.longitude})
else :
print (f"Trying split address for address {addr}")
location = get_coordinates_with_retry(addr.split(',')[0])
if location is not None:
result = pd.Series({'lat': location.latitude, 'lon': location.longitude})
else:
result = pd.Series({'lat': -1, 'lon': -1})
# assign to cache
if useCache:
geo_cache[addr] = result
return(result)
# Use the test data
df = pd.DataFrame({'addr' : [
'IN,Krishnagiri,635115',
'IN,Chennai,600005',
'IN,Karnal,132001',
'IN,Jaipur,302021',
'IN,Chennai,600005']})
# repeat the test data to make alarger set
df = pd.concat([df, df, df, df, df, df, df, df, df, df])
df.addr.apply(get_coordinates)
print(f"Address cache contains {len(geo_cache)} address locations.")
关于python - 使用 API 调用时, throttle Pandas 适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466252/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!