python - 从 nba_api 写入 CSV 时不按行分隔

标签 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 /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")

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)

关于python - 从 nba_api 写入 CSV 时不按行分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728904/

相关文章:

python - 勾选 Python 中的 Python 实例

python - 如何将用户在 Matplotlib 中输入的点传递到 np.array?

python Pandas : how to turn a DataFrame with "factors" into a design matrix for linear regression?

python - 如何在 postgresql 中存储超过 1600 列

regex - sed - 删除大型 csv 文件中引号内的引号

python - 如何使用 Python 旋转 3D 数组而不进行舍入?

python - 计算矩阵中的距离 Pandas Python

python - 获取数据框中以数字开头的所有值

html - 如何在 iOS 上将数据转换为 CSV 或 HTML 格式?

python - 在 Python 中的 CSV 文件顶部插入一行