2017-07-27 38 views
0

我正在从网上抓取与this one(大型击球游戏日志表)完全相同的多个表格,并且我需要数据框忽略以季节开始的内部标题行。忽略熊猫数据框中的内部标题行

这是到目前为止我的脚本:

from bs4 import BeautifulSoup 
import pandas as pd 
import csv 
import urllib2 

def stir_the_soup(): 
    player_links = open('player_links.txt', 'r') 
    player_ID_nums = open('player_ID_nums.txt', 'r') 
    id_nums = [x.rstrip('\n') for x in player_ID_nums] 
    idx = 0 
    for url in player_links: 
     #open the url and create bs object 
     player_link = urllib2.urlopen(url) 
     bs = BeautifulSoup(player_link, 'html5lib') 

     #identify which table is needed 
     table_id = "" 
     if url[-12] == 'b': 
      table_id = "batting" 
     elif url[-12] == 'p': 
      table_id = "pitching" 

     #find the table and create dataframe 
     table = str(bs.find('table', {'id' : (table_id + '_gamelogs')})) 

     df = pd.read_html(table, header=0) 
     df2 = df[0] 
     df2 = df2[df2.PA != 'PA'] 

     #for the name of the file and file path 
     file_path = '/Users/kramerbaseball/Desktop/MLB_Web_Scraping_Program/game_logs_non_concussed/' 
     name_of_file = str(id_nums[idx]) 

     df2.to_csv(path_or_buf=(file_path + name_of_file + '.csv'), sep=',', encoding='utf-8') 
     idx += 1 


if __name__ == "__main__": 
    stir_the_soup() 

我试图以数据帧,而忽略其中PA PA ==或HR == HR但不会删除行的行。任何帮助表示赞赏

回答

1

请注意,在一些内部标题列中值是恒定的。这将降低中间头从df

df3 = df2[df2['Gtm']!='Date'] 
+0

谢谢,这个工作,但为什么它在“GTM”列=“日期”!?他们是单独的列 –

+0

不知道,但船长明显假设列和标题以某种方式相互移动=) –