为了账号安全,请及时绑定邮箱和手机立即绑定

在数据帧 python 中对函数结果进行分组

在数据帧 python 中对函数结果进行分组

翻过高山走不出你 2022-09-06 17:49:50
我有我在谷歌新闻中搜索的请求列表输出在一个列表中给我所有与此新闻的链接rqsts_catdogtiger = ['Cat' , 'Dog', 'Tiger']headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}page=0 #first page of google news (10 first news)url_list = []for term in rqsts_catdogtiger[0:3]:          url = 'https://www.google.com/search?q={}&tbm=nws&start={}'.format(term,page) #url of request    print(url)    url_list.append(url)       soups = []for link in url_list:    response = requests.get(link, headers=headers,verify=False)    soup = BeautifulSoup(response.text, 'html.parser')    soups.append(soup)def find_links():    for soup in soups:        results = soup.findAll("div", {'class': 'g'}) #class of google news        for result in results:            result_link = result.find('a').get('href') #getting links            yield result_linklist_of_links = list(find_links())list_of_links输出看起来像30个链接的列表:10个,10个,10个CatDogTiger我如何将此结果组合成这样:pd.DataFrame    Request Name                   Links0            Cat      'https://www.polygon.com/2020/3/19/21187025/cats-2019-tom-hooper-mr-mistoffelees-broadway-musical',...1            Dog      'https://nypost.com/2020/03/19/second-dog-in-hong-kong-tests-positive-for-coronavirus/',...2          Tiger      'https://tvrain.ru/teleshow/doma_pogovorim/tiger_cave-504935/',...
查看完整描述

1 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

如果我理解你很好,你应该首先通过将列表拆分为均匀长的子列表来准备你的数据:list_of_links


import pandas as pd


rqsts_catdogtiger = ['Cat' , 'Dog', 'Tiger']

list_of_links = [...] # your list of links


n = int(len(list_of_links) / len(rqsts_catdogtiger))

list_of_list_of_links = [list_of_links[i:i + n] for i in range(0, len(list_of_links), n)]

之后,您可以轻松地制作.如果希望列表位于列中,请使用以下代码:pandas.DataFrameLinks


>>> df = pd.DataFrame({'Request Name': rqsts_catdogtiger, 'Links': list_of_list_of_links})

>>> print(df)

  Request Name                                              Links

0          Cat  [https://www.polygon.com/2020/3/19/21187025/ca...

1          Dog  [https://nypost.com/2020/03/19/second-dog-in-h...

2        Tiger  [https://tvrain.ru/teleshow/doma_pogovorim/tig...

如果要在一个长字符串中包含链接,其中每个链接都用逗号分隔,请使用以下代码:


>>> df = pd.DataFrame({'Request Name': rqsts_catdogtiger, 'Links': [', '.join([url for url in l_of_urls]) for l_of_urls in list_of_list_of_links]})

>>> print(df)

  Request Name                                              Links

0          Cat  https://www.polygon.com/2020/3/19/21187025/cat...

1          Dog  https://nypost.com/2020/03/19/second-dog-in-ho...

2        Tiger  https://tvrain.ru/teleshow/doma_pogovorim/tige...


查看完整回答
反对 回复 2022-09-06
  • 1 回答
  • 0 关注
  • 132 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号