python - Python - 使用 Lambda 的 Pandas 脚本太慢
问题描述
我的代码按我的意愿工作,但是当我运行这一行时非常慢。
--- newdf['Login'] = newdf['Site'].apply(lambda x : "yes" if get(x).status_code == 200 else "no") ---
注释后代码运行速度很快。如何更改此行以在登录列中添加“是”或“否”并保持快速?如果我能改进这一切,我将不胜感激。我希望我能理解自己。谢谢!
import pandas as pd
import requests
from requests import get
from requests.exceptions import HTTPError
lista = pd.read_csv('sites4.csv', sep=',')
df = pd.DataFrame(lista, columns=['Site', 'Login'])
newdf = df.assign(Site=df['Site'].map(str) + 'Login')
headers = {'Content-Type': 'application/json'}
for i in newdf['Site']:
try:
result = get(i, headers=headers, timeout=5)
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
else:
if 'application/json' in result.headers.get('Content-Type') or result.status_code == 406 or result.status_code == 403:
newdf['Login'] = newdf['Site'].apply(lambda x : "yes" if get(x).status_code == 200 else "no")
print(i + ' é Login')
print(result)
解决方案
因为 get 在请求中是 func 。
由于 requests 不是异步包,所以所有代码都会中断,直到请求完成。
如果你使用 asyncio 和 aiohttp,你可以改进它。
推荐阅读
- python - 具有枚举编码的 Protobuf oneof 字段
- c# - NPGSQL 开始文本导入在较大的 CSV 文件上引发异常
- javascript - 使用 react-redux 时,prevProps 和 this.props 将始终在 componentDidUpdate 中返回相同的值
- mysql - MySQL - 多个并发更新
- c - 第 25 行中的运行时错误:字符 35:运行时错误:“struct HASH_TABLE”类型的空指针内的成员访问(solution.c)
- android - 如何在不使用库的情况下在状态、焦点和正常状态下应用自定义形状的 TextInputLayout
- python - 记录学生姓名的功能
- xcode - 图像作为图标外观
- c - 即使我包含 unistd.h 在内核代码中隐式声明 getpid
- amazon-web-services - 如何使用 Eclipse JEE 从我的 Web 应用程序登录到 AWS?