从nba_api写入CSV不会按行分开

时间:2019-02-17 00:08:40

标签: python pandas csv

我正在尝试从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")

输出结果如下:enter image description here https://imgur.com/a/YdqoR6p

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?

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")

enter image description here

或更简单的方法:

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)