You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python函数中返回多个URL合并后的DataFrame?

解决多个URL提取的DataFrame合并问题

你的问题核心是:循环中每次都会覆盖fullbox变量,最终返回的只是最后一次循环生成的DataFrame,而非所有结果的合并。要实现所有DataFrame的合并,需要先收集每个URL生成的结果,再统一合并。

修改后的代码如下:

import pandas as pd

urllist = ['https://basketball.realgm.com/nba/boxscore/2022-04-09/Indiana-at-Philadelphia/388705', 
           'https://basketball.realgm.com/nba/boxscore/2022-04-09/New-Orleans-at-Memphis/388704', 
           'https://basketball.realgm.com/nba/boxscore/2022-04-09/Golden-State-at-San-Antonio/388706', 
           'https://basketball.realgm.com/nba/boxscore/2022-04-09/Sacramento-at-LA-Clippers/388703']

def Boxscore(URL):
    # 初始化空列表存储每个URL的DataFrame
    all_boxes = []
    for x in URL:
        box_list = pd.read_html(x)
        box1 = box_list[3]
        box2 = box_list[4]
        fullbox = pd.concat([box1, box2])
        all_boxes.append(fullbox)
    # 合并列表中所有DataFrame,重置索引避免重复
    return pd.concat(all_boxes, ignore_index=True)

fullboxscore = Boxscore(urllist)
print(fullboxscore)

关键改动说明:

  • 新增all_boxes列表,用来逐个存储每个URL处理后的fullbox结果
  • 循环结束后,调用pd.concat合并列表内所有DataFrame,ignore_index=True参数可以重置合并后的索引,避免不同来源DataFrame的索引冲突问题

内容的提问来源于stack exchange,提问作者clay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:35:36