首页 > 解决方案 > 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)

标签: pythonpandaslambda

解决方案


因为 get 在请求中是 func 。

由于 requests 不是异步包,所以所有代码都会中断,直到请求完成。

如果你使用 asyncio 和 aiohttp,你可以改进它。


推荐阅读