Объедините фреймы данных в конце al oop для очистки веб-страницы - PullRequest
0 голосов
/ 07 августа 2020

Я начал писать программу для веб-вырезания таблицы данных из нескольких URL-адресов. Я дошел до того момента, когда я создаю список URL-адресов из импорта электронной таблицы Excel, l oop через список URL-адресов и очищаю определенную c таблицу на веб-странице путем поиска заголовка таблицы.

Оператор печати в конце l oop распечатывает отдельную таблицу для каждого URL-адреса отдельно. Есть ли простой способ добавить () строки DataFrame вместе, как при создании простого списка? Таблицы имеют одинаковую раскладку.

from urllib.request import urlopen
from bs4 import BeautifulSoup, NavigableString, Tag
import requests
import pandas as pd
import re
import ssl
import lxml
import xlrd
import csv

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

#auto import excel file
ex = pd.read_excel(r'/Users/adamsewell/Desktop/GB_Basketball/Data/GB_Player_Tracking_Document.xlsm', sheet_name='Player URL')
yr = '2019-20'

#list urls from excel sheet
url_list = ex['URL'].tolist()

for url in url_list:
    #first header as a reference point
    table_title = 'International Regular Season Stats - Per Game'
    #replace to gain second header title to end loop
    second_header = (table_title.replace(' Per Game',' Totals'))

    html = urlopen(url, context=ctx).read()
    soup = BeautifulSoup(html, "html.parser")

    #find the table in the whole HTML
    start = soup.find('h2', text=table_title)
    end = soup.find('h2', text=second_header)
    content = '' #prime content as nothing
    item = start.nextSibling

    #while not at the end header, add content to the item
    while item != end:
        content += str(item)
        item = item.nextSibling

    #create a list and concat to a dataframe table
    dfs = pd.read_html(content)
    df = pd.concat(dfs)

    #remove unwanted row (if not year of interest)
    indexNames = df[(df['Season'] != yr) & (df['Season'] != yr + ' *')].index
    df.drop(indexNames, inplace=True)

    #abstract players name from GM URL
    name_split = url.split('/')
    players_name = (name_split[4].replace('-', ' '))

    #Add column of player name, add player name from URL, and move to first column
    df['Player Name'] = players_name
    col_name = 'Player Name'
    first_col = df.pop(col_name)
    df.head
    df.insert(0,'Player Name', first_col)
    print(df)

Я новичок в программировании и только начал использовать python около 3 недель go, поэтому чем проще ответ, тем лучше! Спасибо

Ответы [ 2 ]

0 голосов
/ 08 августа 2020

Я немного покопался и нашел решение в предыдущем ответе по следующей ссылке

#set new df 
real_gm_append = []

for url in url_list:
........................

    #append to new data frame
    real_gm_append.append(df)

real_gm_append = pd.concat(real_gm_append)
print(real_gm_append)
0 голосов
/ 07 августа 2020

Если я понимаю требование, вы просто хотите объединить весь фрейм данных в один фрейм данных.

Попробуйте этот код:

dfFull = None
for url in url_list:
    .........
    print(df)
    if dfFull == None: 
        dfFull = df  # start with first set
    else:  # append new df
        dfFull.append(df, ignore_index=True) 

print(dfFull)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...