![](/img/trans.png)
[英]Write each row of pandas dataframe into a new text file - pythonic way
[英]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
以前有人這樣做過嗎? 我試圖自己解決這個問題,但它只是讓我手動轉錄。 如果需要更清楚,請告訴我。
鑒於人行橫道xwalk
之間team_id
和team_name
其中team_name
有一個一到一個完美匹配HomeTeam
等:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.