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

为什么pandas使用append拼接DataFrame时仅保留最后一个文件的数据?

问题原因
  • 你使用的DataFrame.append接口已在Pandas 1.4版本弃用,2.0及以上版本已正式移除,兼容版本的实现本身存在偶发拼接异常,这是你遇到问题的核心诱因。
  • 检查代码缩进:你贴出的代码中return语句缩进层级和for循环齐平,如果实际运行时return写在for循环内部,会导致循环执行一次就提前返回,不过结合你给出的现象该情况概率较低。
  • 核对入参类型:你标注upload_files是字符串列表,但代码中使用了file.name取值,字符串没有name属性,如果运行时没有报错,说明你实际传入的是文件对象,和你给出的示例类型不符,可能引发预期外的取值错误。
  • 排查文件结构:如果不同DBF文件导出的DataFrame列名完全不匹配,也可能出现拼接后行数异常的情况,该场景通常会伴随大量NaN值。
修复方案

改用更稳定的pd.concat实现多DataFrame拼接,避免反复append带来的性能损耗和逻辑异常,修改后代码如下:

def show_files(upload_files):
    # 用列表暂存所有分片DataFrame,最后一次性拼接,逻辑更稳定
    l_df_list = []
    m_df_list = []

    for file in upload_files:
        # 如果upload_files确实是字符串列表,直接用file即可,不需要取.name属性
        file_name = file.name
        table = Dbf5(file_name)
        current_df = table.to_dataframe()
        if file_name.startswith('L'):
            l_df_list.append(current_df)
        elif file_name.startswith('M'):
            m_df_list.append(current_df)
            print(f"加载{file_name}完成,当前文件行数:{len(current_df)}")
    
    # 一次性拼接所有同类型DataFrame
    tempDF = pd.concat(l_df_list, ignore_index=True, sort=False) if l_df_list else pd.DataFrame()
    tempDF2 = pd.concat(m_df_list, ignore_index=True, sort=False) if m_df_list else pd.DataFrame()
    print(f"final 2 - 总行数:{len(tempDF2)}")
    return [tempDF, tempDF2]

注意:如果你的upload_files确实为你示例中给出的字符串列表,需要把file_name = file.name改为file_name = file,否则会直接抛出属性错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:12:00