我正在尝试从 python NBA_API 中提取以前的 NBA 比赛,但我的格式无法按照我的需要进行。我希望将数据流中的每一行分离到列中的每个行
import nba_api
import requests
import csv
from nba_api.stats.static import teams
from nba_api.stats.endpoints import leaguegamefinder
from nba_api.stats.endpoints import leaguegamelog
season = leaguegamelog.LeagueGameLog("00")
nba_teams = teams.get_teams()
seasonGames = season.get_data_frames()[0]
seasonGames.head()
print(seasonGames.TEAM_NAME)
with open('NBAStats.csv', mode='w') as csv_file:
fieldnames = ['team_name','team_id','game_id']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames,delimiter=',')
writer.writeheader()
for TEAM_NAME in seasonGames['TEAM_NAME']:
writer.writerow({'team_name': seasonGames["TEAM_NAME"],'team_id': seasonGames["TEAM_ID"],'game_id': seasonGames["GAME_ID"]})
print("done")
输出如下所示: /image/Zpokg.jpg
最佳答案
这是你想要的吗?
import csv
from nba_api.stats.endpoints import leaguegamelog
season = leaguegamelog.LeagueGameLog("00")
seasonGames = season.get_data_frames()[0]
with open('NBAStats.csv', mode='w') as csv_file:
fieldnames = ['team_name','team_id','game_id']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames,delimiter=',', lineterminator='\n')
writer.writeheader()
for group in seasonGames.groupby("TEAM_NAME"):
TEAM_NAME, group_df = group
for ix in group_df.index:
writer.writerow({'team_name': group_df.loc[ix, "TEAM_NAME"],
'team_id': group_df.loc[ix, "TEAM_ID"],
'game_id': group_df.loc[ix, "GAME_ID"]})
print("done")
或者使用更简单的方法:
import csv
from nba_api.stats.endpoints import leaguegamelog
season = leaguegamelog.LeagueGameLog("00")
seasonGames = season.get_data_frames()[0]
opDF = seasonGames.sort_values(by=["TEAM_NAME", "GAME_ID"])[["TEAM_NAME", "TEAM_ID", "GAME_ID"]]
opDF.columns = [["team_name", "team_id", "game_id"]]
opDF.to_csv('NBAStats.csv', index=False)
关于python - 从 nba_api 写入 CSV 时不按行分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728904/