【问题标题】:Apply a Function to a Dictionary in Python在 Python 中将函数应用于字典
【发布时间】:2020-01-29 23:50:07
【问题描述】:

我有一个 ELIF 函数来确定网站是否存在。 elif 有效,但速度非常慢。我想创建一个字典来将 ELIF 函数应用于我拥有的 URL 列表。理想情况下,我希望将输出放入一个列出 URL 和函数结果的新表中。

我正在为下面发布的 elif 声明中列出的潜在输出创建一个字典

check = {401:'web site exists, permission needed', 404:'web site does not exist'}





for row in df['sp_online']:
    r = requests.head(row)
    if r.status_code == 401:
        print ('web site exists, permission needed')
    elif r.status_code == 404:
        print('web site does  not exist')
else:
        print('other')

如何获得确认功能的结果,以将每个 url 的结果显示为数据框中的新列?

【问题讨论】:

  • 你的问题是什么?
  • 抱歉,我会更新帖子。我不知道如何将确认功能应用于数据帧我必须将结果显示为原始数据帧中每一行的新列

标签: python function dataframe dictionary url


【解决方案1】:

我想你在找Series.map

df = pd.DataFrame({'status': [401, 404, 500]})
check = {401:'web site exists, permission needed', 404:'web site does not exist'}
print(df['status'].map(check))

打印

0    web site exists, permission needed
1               web site does not exist
2                                   NaN
Name: status, dtype: object

以正常方式分配给新列

df['new_col'] = df['status'].map(check)

【讨论】:

    【解决方案2】:

    我认为您应该尝试线程或多处理方法。您可以汇集 n 个网站并等待他们的响应,而不是一次请求一个站点。使用ThreadPool,您可以通过几行额外的代码来实现这一点。希望对你有用!

    import requests
    from multiprocessing.pool import ThreadPool
    
    list_sites = ['https://www.wikipedia.org/', 'https://youtube.com', 'https://my-site-that-does-not-exist.com.does.not']
    
    def get_site_status(site):
        try:
            response = requests.get(site)
        except requests.exceptions.ConnectionError:
            print("Connection refused")
            return 1
        if response.status_code == 401:
            print('web site exists, permission needed')
        elif response.status_code == 404:
            print('web site does  not exist')
        else:
            print('other')
        return 0
    
    pool = ThreadPool(processes=1)
    
    results = pool.map_async(get_site_status, list_sites)
    
    print('Results: {}'.format(results.get()))
    

    【讨论】:

    • 谢谢,拉斐尔。这正是我想要的。
    猜你喜欢
    • 2019-12-05
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多