首页 > 解决方案 > 将函数返回的键值作为新列附加到 Dataframe

问题描述

我有一个数据框,其中包含我想提取几个值的 url 列表。然后应将返回的键/值添加到原始数据框中,其中键作为新列和相应的值。

我认为这会神奇地发生 result_type='expand',但显然不会。当我尝试

df5["data"] = df5.apply(lambda x: request_function(x['url']),axis=1, result_type='expand')

我最终将结果全部放在一个数据列中:

[{'title': ['Python Notebooks: Connect to Google Search Console API and Extract Data - Adapt'], 'description': []}]

我的目标是一个包含以下 3 列的数据框:

| URL|      Title      |  Description|

这是我的代码:

import requests
from requests_html import HTMLSession
import pandas as pd
from urllib import parse

ex_dic = {'url': ['https://www.searchenginejournal.com/reorganizing-xml-sitemaps-python/295539/', 'https://searchengineland.com/check-urls-indexed-google-using-python-259773', 'https://adaptpartners.com/technical-seo/python-notebooks-connect-to-google-search-console-api-and-extract-data/']}

df5 = pd.DataFrame(ex_dic)
df5

def request_function(url):
    try:
        found_results = []
        r = session.get(url)
        title = r.html.xpath('//title/text()')
        description = r.html.xpath("//meta[@name='description']/@content")
        found_results.append({ 'title': title, 'description': description})
        return found_results


    except requests.RequestException:
        print("Connectivity error")      
    except (KeyError):
        print("anoter error")

df5.apply(lambda x: request_function(x['url']),axis=1, result_type='expand')

标签: pythonpandas

解决方案


ex_dic应该是字典列表,以便您可以更新应用的属性。

import requests
from requests_html import HTMLSession
import pandas as pd
from urllib import parse

ex_dic = {'url': ['https://www.searchenginejournal.com/reorganizing-xml-sitemaps-python/295539/', 'https://searchengineland.com/check-urls-indexed-google-using-python-259773', 'https://adaptpartners.com/technical-seo/python-notebooks-connect-to-google-search-console-api-and-extract-data/']}

ex_dic['url'] = [{'url': item} for item in ex_dic['url']]

df5 = pd.DataFrame(ex_dic)
session = HTMLSession()

def request_function(url):
    try:
        print(url)
        r = session.get(url['url'])
        title = r.html.xpath('//title/text()')
        description = r.html.xpath("//meta[@name='description']/@content")
        url.update({ 'title': title, 'description': description})
        return url


    except requests.RequestException:
        print("Connectivity error")      
    except (KeyError):
        print("anoter error")

df6 = df5.apply(lambda x: request_function(x['url']),axis=1, result_type='expand')
print df6

推荐阅读