【发布时间】:2019-12-12 10:54:21
【问题描述】:
我正在从一个基本 URL 构建一个自动 MLB 时间表,并在 URL 中出现的团队名称列表中循环。使用 pd.read_html 我得到每个团队的日程安排。对于每个团队的页面,我唯一缺少的是团队名称本身,我希望将其作为新列“team_name”。在这篇文章的结尾,我有一个目标的小样本。
下面是我目前所拥有的,如果你运行它,打印出来的结果正是我需要的一个团队。
import pandas as pd
url_base = "https://www.teamrankings.com/mlb/team/"
team_list = ['seattle-mariners']
df = pd.DataFrame()
for team in (team_list):
new_url = url_base + team
df = df.append(pd.read_html(new_url)[1])
df['team_name'] = team
print(df[['team_name', 'Opponent']])
问题是,当我在 team_list 中拥有所有 30 个团队时,team_name 的值不断被覆盖,因此所有 4000 多条记录都列出了相同的团队名称(team_list 中的最后一个)。我尝试使用
仅动态分配团队值的某些行df['team_name'][a:b] = team
其中 a、b 是索引团队数据帧上的起始行和结束行;但这给出了 KeyError:'team_name'。我也尝试过为 team_name 使用占位符系列和数据框,然后与 df 合并,但会出现重复错误。在更大的范围内,我正在寻找的是:
team_name opponent
0 seattle-mariners new-york-yankees
1 seattle-mariners new-york-yankees
2 seattle-mariners boston-red-sox
3 seattle-mariners boston-red-sox
4 seattle-mariners san-diego-padres
5 seattle-mariners san-diego-padres
6 cincinatti-reds new-york-yankees
7 cincinatti-reds new-york-yankees
8 cincinatti-reds boston-red-sox
9 cincinatti-reds boston-red-sox
10 cincinatti-reds san-diego-padres
11 cincinatti-reds san-diego-padres
【问题讨论】:
标签: python python-3.x pandas dataframe for-loop