亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在循環結束時將行添加到 pandas 數據框

在循環結束時將行添加到 pandas 數據框

qq_遁去的一_1 2023-06-20 13:29:36
我正在嘗試在數據框中添加行作為循環的一部分。該程序循環訪問 URL 并以數據幀格式提取數據for id in game_ids:    df_team_final = []    df_player_final = []    url = 'https://www.fibalivestats.com/data/' + id + '/data.json'    content = requests.get(url)    data = json.loads(content.content)在循環結束時,我使用 concat 合并客隊/主隊(和球員)的兩個 df    team_full = pd.concat([df_home_team, df_away_team])    player_full = pd.concat([df_home_player_merge, df_away_player_merge])在循環外我已經編程保存為 Excel# #if cant find it, create new spread sheetwriter = pd.ExcelWriter('Box Data.xlsx', engine='openpyxl')team_full.to_excel(writer, sheet_name='Team Stats', index=False)player_full.to_excel(writer, sheet_name='Player Stats', index=False)writer.save()writer.close()當我循環瀏覽多個網頁時,我需要隨時更新 df,顯然在當前格式中,我只是用第二個循環覆蓋第一個 url在循環結束時附加或添加到數據幀的最佳方法是什么?
查看完整描述

1 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

由于我們看不到完整的代碼,因此我只能在這里給出一個粗略的輪廓。


我假設您沒有將抓取的數據附加到某種容器,因此它會在下一次迭代后丟失。


# empty lists outside of loop to store data

df_team_final = []

df_player_final = []


for id in game_ids:

    url = 'https://www.fibalivestats.com/data/' + id + '/data.json'

    content = requests.get(url)

    data = json.loads(content.content)


    # create dataframes that you need

    # df_home_team, df_away_team etc

    # and append data to containers


    team_full = pd.concat([df_home_team, df_away_team])

    player_full = pd.concat([df_home_player_merge, df_away_player_merge])


    df_team_final.append(team_full)

    df_player_final.append(player_full )

現在您將數據框存儲為列表,您可以將它們與pandas.concat


# outside of the loop

team_full = pd.concat(df_team_final)

player_full = pd.concat(df_player_final)

并立即保存:


writer = pd.ExcelWriter('Box Data.xlsx', engine='openpyxl')

team_full.to_excel(writer, sheet_name='Team Stats', index=False)

player_full.to_excel(writer, sheet_name='Player Stats', index=False)

writer.save()

writer.close()

編輯

從您共享的文件中,我看到您在循環中添加了容器:

http://img1.sycdn.imooc.com//649139600001069504090178.jpg

但是你應該把它們放在循環開始之前:


# initialize them here

df_team_final = []

df_player_final = []

for id in game_ids:


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號