2016-04-14 45 views
1

我想刮http://www.basketball-reference.com/awards/all_league.html一些分析,我的目標是一樣的東西下面轉換多列到單個基於另一列值蟒蛇

0 1日馬克 - 加索爾2014至2015年
1月1日安東尼 - 戴維斯2014- 2015
2第一詹姆斯2014-2015年
3個第一哈登2014-2015年
4第一庫裏2014-2015年
5第二保羅加索爾2014 - 2015年等

這是我迄今爲止的代碼,無論如何要做到這一點?任何建議/幫助非常感謝。

r = requests.get('http://www.basketball-reference.com/awards/all_league.html') 
soup=BeautifulSoup(r.text.replace(' ','').replace('>','').encode('ascii','ignore'),"html.parser") 
all_league_data = pd.DataFrame(columns = ['year','team','player']) 


stw_list = soup.findAll('div', attrs={'class': 'stw'}) # Find all 'stw's' 
for stw in stw_list: 
    table = stw.find('table', attrs = {'class':'no_highlight stats_table'}) 
    for row in table.findAll('tr'): 
     col = row.findAll('td') 
     if col: 
      year = col[0].find(text=True) 
      team = col[2].find(text=True) 
      player = col[3].find(text=True) 
      all_league_data.loc[len(all_league_data)] = [team, player, year] 
    all_league_data 

回答

1

看起來你的代碼應該可以正常工作,但這裏沒有大熊貓的工作版本:您正在使用的大熊貓所以使用read_html

import pandas as pd 

all_league_data = pd.read_html('http://www.basketball-reference.com/awards/all_league.html') 
print(all_league_data) 

,這將給你所有

import requests 
from bs4 import BeautifulSoup 

r = requests.get('http://www.basketball-reference.com/awards/all_league.html') 
soup=BeautifulSoup(r.text.replace(' ','').replace('>','').encode('ascii','ignore'),"html.parser") 
all_league_data = [] 

stw_list = soup.findAll('div', attrs={'class': 'stw'}) # Find all 'stw's' 
for stw in stw_list: 
    table = stw.find('table', attrs = {'class':'no_highlight stats_table'}) 
    for row in table.findAll('tr'): 
     col = row.findAll('td') 
     if col: 
      year = col[0].find(text=True) 
      team = col[2].find(text=True) 
      player = col[3].find(text=True) 
      all_league_data.append([team, player, year]) 

for i, line in enumerate(all_league_data): 
    print(i, *line) 
1

數據框中的表格數據:

In [7]: print(all_league_data[0].dropna().head(5)) 
     0 1 2     3     4 \ 
0 2014-15 NBA 1st  Marc Gasol C  Anthony Davis F 
1 2014-15 NBA 2nd  Pau Gasol C DeMarcus Cousins C 
2 2014-15 NBA 3rd DeAndre Jordan C  Tim Duncan F 
4 2013-14 NBA 1st  Joakim Noah C  LeBron James F 
5 2013-14 NBA 2nd Dwight Howard C  Blake Griffin F 

        5    6     7 
0  LeBron James F James Harden G  Stephen Curry G 
1 LaMarcus Aldridge F  Chris Paul G Russell Westbrook G 
2  Blake Griffin F Kyrie Irving G  Klay Thompson G 
4  Kevin Durant F James Harden G   Chris Paul G 
5   Kevin Love F Stephen Curry G  Tony Parker G 

重新排列無論你喜歡還是放棄某些列都是微不足道的,read_html需要像attrs這樣的幾個參數,你也可以應用它,它全部在鏈接中。