2017-10-18 130 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

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