2017-10-18 132 views
1

我正在構建幻想足球的預測模型。我使用Beautiful Soup颳了一個網站,將數據解析成列表,創建了一個數據框,並用適當的列表填充了兩列。解析代碼如下所示:用列表中的項目填充熊貓數據框

stats = [] 
team_list = [] 
vs_list = [] 
for idx in range(len(parsed_stats)): 
    try: 
     stats.append(float(parsed_stats[idx][0])) 
    except: 
     if len(parsed_stats[idx]) > 1: 
      team_list.append(parsed_stats[idx][4]) 
      vs_list.append(parsed_stats[idx+1][0].replace('@', '')) 

qb.team, qb.vs = team_list, vs_list 

我有38行需要如此填充現在我的數據幀的頭看起來是這樣的:

player_id name team vs ffpts patt pcmp pyds ptds pint p2 ratt ryds rtds r2 fum td 
0 1 Matt Ryan Atl KC 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
1 2 Tony Romo Dal NYG 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
2 3 Robert Griffin III Griffin, NO 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
3 4 Drew Brees NO Was 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
4 5 Mark Sanchez NYJ Buf 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 

的零點需要填充與數據統計列表中的項目。我哪個索引正確編碼此嵌套的for循環:

for idx,row in enumerate(qb.values): 
    count = 4 
    while count < 17: 
     for val in stats: 
      qb.iloc[idx,count] = val 
     count +=1 

環路指向右側細胞但用零填充,而不是統計項目整個數據幀。 parsed_stats列表和其他代碼在我的git集線器上: my git hub 任何想法?

+0

只要給出反饋,我不知道'parsed_stats'是什麼。我希望你提供這個,以便我們可以嘗試。我無法解析你的數據框......這等同於我不得不努力去幫助你。 – piRSquared

+0

感謝您的反饋。我編輯我的帖子,包括我的git集線器。你可以在那裏找到它。再次感謝。 –

回答

0

在創建初始數據框之前,我將最後一列的名稱更改爲vs_2,因爲您已經有一列名爲vs的列。在此之後,下面似乎工作:

remaining_columns = columns[4:] 
for num, col in enumerate(remaining_columns, start=2): 
    print(num, col) 
    # Flatten the list and assign it to the relevant column 
    flat_list = [item for sublist in parsed_stats[num:][::19] for item in sublist] 
    qb[col] = flat_list 
qb.iloc[0] 
 
player_id   1 
name   Matt Ryan 
team    Atl 
vs     KC 
ffpts   37.00 
pass_att   31 
pass_comp   23 
pass_yds   299 
pass_tds    3 
int     0 
pass2    0 
rush_att    3 
rush_yds   25 
rush_tds    1 
rush_2    0 
rec     0 
rec_yds    0 
rec_tds    0 
rec_2    0 
fum     0 
vs_2     0 
Name: 0, dtype: object 

請仔細檢查,一切都以正確的順序和這些數字是有意義的,我不是美式足球,以評估它足夠熟悉。

+0

超棒的男人。謝了,兄弟!!!! –