数据帧未按预期工作

2024-04-25 16:37:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我用熊猫放在桌子上的链接:

http://sports.yahoo.com/nfl/stats/byposition?pos=QB&conference=NFL&year=season_2014&sort=49&timeframe=All

我正在尝试从每一行(相关)创建播放器对象。所以我想从第三排一直到终点,我用一堆不同的字段来构造一个球员对象,包括名字,球队,传球码等等

以下是我的尝试:

def getAllQBs():
    QBs = []
    table = pd.read_html(requests.get(QB_LINK).content)[5]
    finalTable = table[2 : ]
    print(finalTable)

    for row in finalTable.iterrows():
        print(row)
        name = row[0]
        team = row[1]
        passingYards = row[7]
        passingTouchdowns = row[10]
        interceptions = row[11]
        rushingYards = row[13]
        rushingTouchdowns = row[16]
        rushingFumbles = row[19]
        newQB = QB(name, team, rushingYards, rushingTouchdowns, rushingFumbles, passingYards, passingTouchdowns, interceptions)
        QBs.append(newQB)
        print(newQB.toString())
    return QBs

Passing yards是该行左边的第8个元素,所以我想我应该使用row[7]来访问它。但是,当我运行此函数时,我得到:

Traceback (most recent call last):
  File "main.py", line 66, in <module>
    main()
  File "main.py", line 64, in main
    getAllQBs()
  File "main.py", line 27, in getAllQBs
    passingYards = row[7]
IndexError: tuple index out of range

看起来我无意中使用了列。但是,我使用了DataFrame.iterrows(),我认为这会解决这个问题。。。你知道吗

有什么想法吗?你知道吗

谢谢你, B外行


Tags: 对象inpymainlinetablefilerow
1条回答
网友
1楼 · 发布于 2024-04-25 16:37:40

iterrows()生成(index, Series)形式的元组,其中Series是您尝试访问的行数据。在这种情况下,如果索引没有意义,可以将其解压为伪变量,如下所示。你知道吗

for (_, row) in finalTable.iterrows():
    .....

相关问题 更多 >

    热门问题