有没有一种方法可以逐行循环遍历 pandas 数据帧,并将每一行与相应的团队 ID 和结果作为一行打印到文本文件中?
Is there a way to loop through a pandas dataframe by row and print each row as a line with the corresponding team id and results to a text file?
我在包含 EPL 比赛结果的数据框中导入了一个 csv,并在一个文本文件中导入了包含每个球队名称和球队 ID 号的文本文件。
df_results:
HomeTeam AwayTeam HomeGoals AwayGoals
0 Man United Leicester 2 1
1 Bournemouth Cardiff 2 0
2 Fulham Crystal Palace 0 2
3 Huddersfield Chelsea 0 3
4 Newcastle Tottenham 1 2
teams.txt:
1, Man United
2, Bournemouth
3, Fulham
4, Huddersfield
5, Newcastle
6, Watford
7, Wolves
8, Arsenal
9, Liverpool
10, Southampton
11, Cardiff
12, Chelsea
13, Everton
14, Leicester
15, Tottenham
16, West Ham
17, Brighton
18, Burnley
19, Man City
20, Crystal Palace
有没有办法逐行循环遍历 pandas 数据帧,并将每一行与相应的团队 ID 和结果一起打印到文本文件中,并以逗号分隔?
例如:
0 Man United Leicester 2 1
最终结果:
1, 1, 2, 14, -1, 1
First column = home team id
Second column = 1
Third column = HomeGoals
Fourth column = Away Team id
Fifth column = -1
Sixth column = AwayGoals
文本文件最终看起来像这样:
1, 1, 2, 14, -1, 1
2, 1, 2, 11, -1, 0
3, 1, 0, 20, -1, 2
4, 1, 0, 12, -1, 3
5, 1, 1, 15, -1, 2
以前有人做过吗?我试图自己解决这个问题,但它只是让我手动转录这个。如果需要更清楚的说明,请告诉我。
给定 team_id
和 team_name
之间的人行横道 xwalk
,其中 team_name
与 HomeTeam
等 one-to-one 完美匹配:
df['home_team_id'] = df['HomeTeam'].map(xwalk.set_index('team_name')['team_id'])
df['away_team_id'] = df['AwayTeam'].map(xwalk.set_index('team_name')['team_id'])
然后按您想要的顺序重新排列您的列并打印为 CSV 传递 header=False
。您可能需要通过分配 df['column_name'] = -1
等来创建列 -1
和 1
我在包含 EPL 比赛结果的数据框中导入了一个 csv,并在一个文本文件中导入了包含每个球队名称和球队 ID 号的文本文件。
df_results:
HomeTeam AwayTeam HomeGoals AwayGoals
0 Man United Leicester 2 1
1 Bournemouth Cardiff 2 0
2 Fulham Crystal Palace 0 2
3 Huddersfield Chelsea 0 3
4 Newcastle Tottenham 1 2
teams.txt:
1, Man United
2, Bournemouth
3, Fulham
4, Huddersfield
5, Newcastle
6, Watford
7, Wolves
8, Arsenal
9, Liverpool
10, Southampton
11, Cardiff
12, Chelsea
13, Everton
14, Leicester
15, Tottenham
16, West Ham
17, Brighton
18, Burnley
19, Man City
20, Crystal Palace
有没有办法逐行循环遍历 pandas 数据帧,并将每一行与相应的团队 ID 和结果一起打印到文本文件中,并以逗号分隔?
例如:
0 Man United Leicester 2 1
最终结果:
1, 1, 2, 14, -1, 1
First column = home team id
Second column = 1
Third column = HomeGoals
Fourth column = Away Team id
Fifth column = -1
Sixth column = AwayGoals
文本文件最终看起来像这样:
1, 1, 2, 14, -1, 1
2, 1, 2, 11, -1, 0
3, 1, 0, 20, -1, 2
4, 1, 0, 12, -1, 3
5, 1, 1, 15, -1, 2
以前有人做过吗?我试图自己解决这个问题,但它只是让我手动转录这个。如果需要更清楚的说明,请告诉我。
给定 team_id
和 team_name
之间的人行横道 xwalk
,其中 team_name
与 HomeTeam
等 one-to-one 完美匹配:
df['home_team_id'] = df['HomeTeam'].map(xwalk.set_index('team_name')['team_id'])
df['away_team_id'] = df['AwayTeam'].map(xwalk.set_index('team_name')['team_id'])
然后按您想要的顺序重新排列您的列并打印为 CSV 传递 header=False
。您可能需要通过分配 df['column_name'] = -1
等来创建列 -1
和 1