【发布时间】:2021-09-11 13:41:51
【问题描述】:
我的代码按我的意愿运行,但是当我运行这一行时非常慢。
--- 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)
【问题讨论】:
-
您是否意识到该行适用于数据框中的每一行?
-
是的,这正是我想要的。我想检查我的数据框的每一行,看看是否返回 200 并在我的 csv 中添加一个 YES。
-
现在您正在使用
for循环遍历数据框,GET:ing 每个 URL。对于每个不返回错误但返回 JSON、403 或 406 的 URL,您将再次获得 all URL:s(不仅仅是您刚刚测试的那个)并更新整个数据帧。这真的是你想要的吗? -
哦,我明白了!谢谢你!