基于同一数据帧中另一列内容的条件,在数据帧中添加新列

2024-06-26 13:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

import requests
from bs4 import BeautifulSoup
import pandas as pd
import re

header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

def scrap_hrefs(url,baseUrl):
    resp = requests.get(url, headers= header)
    respData = BeautifulSoup(resp.content, 'html.parser')     
    allHrefs = respData.select('[href]')
    
    return allHrefs, baseUrl
    
    
def get_hrefs(allHrefs, baseUrl):
    for i in range(0,len(allHrefs)):
        if allHrefs[i]['href'].startswith('/'):
            allHrefs[i]= baseUrl + allHrefs[i]['href']
        else:
            allHrefs[i]= allHrefs[i]['href']
            
    return allHrefs

def clean_hrefs(allHrefs): 
    links = {'links' : allHrefs}
    df = pd.DataFrame(links).drop_duplicates()
    df = df[df['links'].str.contains('financial|investors|investor|Investors|Investor|INVESTORS|INVESTOR|relations|relation|Relations|Relation|report|filings|news|media')]
    for i in range(0,len(df)):
        if df[i]['links'].str.find('financial|investors|investor|Investors|Investor|INVESTORS|INVESTOR|relations|relation|Relations|Relation|report|filings')!= -1:
            df[i]['segments'] = df['Finance']
        else:
            continue
    
    return df
    
def store_hrefs(df):       
    df.to_csv("testing.csv", index=False)
   
    
def run_scraper(url,baseUrl) :
    store_hrefs(clean_hrefs(get_hrefs(*scrap_hrefs(url, baseUrl))))
     
    
run_scraper('https://www.example.com/','https://www.example.com')

在clean_hrefs()函数中,我想从数据框中获取第一个链接,检查它的内容是否包含“finance、investors、ir、report、Fillings”一词。如果有,请创建另一个名为“segments”的列,并将其id指定为“FINANCE”。 但这是一个错误KeyError:0 任何帮助都将不胜感激


Tags: importreportcleanurldfgetreturndef
1条回答
网友
1楼 · 发布于 2024-06-26 13:25:57

如果没有匹配的get缺失值,则可以通过掩码将列设置为另一列,类似于过滤:

mask = df['links'].str.contains('financial|investors|investor|Investors|Investor|INVESTORS|INVESTOR|relations|relation|Relations|Relation|report|filings')
df.loc[mask, 'segments'] = 'Finance'

工作方式如下:

df['segments'] = np.where(mask, 'Finance', np.nan)

编辑:

如果要设置多个值,可以在字典中指定新值,然后设置列segments,如:

d = {'INVESTOR':'financial|investors|investor|Investors|Investor|INVESTORS|INVESTOR|relations|relation|Relations|Relation|report|filings',
     'NEWS':'news|media'}

for k, v in d.items():
    df.loc[df['links'].str.contains(v, na=False), 'segmentID'] = k

相关问题 更多 >