使用异步方法填充Pandas DataFrame
我刚刚看了Idently的这个很棒的视频,然后尝试用里面的方法来根据另一个数据框填充一些列。
这是我的最小可重现示例(其实更像是个不工作的例子),我是在Jupyter笔记本里写的代码。
import asyncio
import pandas as pd
import requests
mydf = pd.DataFrame({'url':['https://google.com','https://apple.com']})
print(mydf)
print("-----")
async def fetch_status(url:str) -> int:
response = await asyncio.to_thread(requests.get,url)
return(response.status_code)
async def main_task() -> None:
myTask = asyncio.create_task(mydf['url'].apply(fetch_status))
mydf['status'] = await myTask
print(mydf)
在一个单独的单元格里:
asyncio.run(main = main_task())
我遇到了一个错误,提示是RuntimeError: asyncio.run() cannot be called from a running event loop
。
有人知道为什么吗?任何帮助都很欢迎。
1 个回答
0
把你的代码分开并修正成这样:
第一部分:
import asyncio
from asyncio import Task
import pandas as pd
import requests
mydf = pd.DataFrame({'url':['http://google.com','http://apple.com']})
print(mydf)
async def fetch_status(url:str) -> int:
response = await asyncio.to_thread(requests.get,url,None)
return(response.status_code)
async def main_task() -> None:
mydf['status'] = await asyncio.gather(*[fetch_status(url) for url in mydf['url']])
第二部分:
await main_task()