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

如何基于非空条件将一个DataFrame追加到另一个DataFrame中

解决DataFrame非空时追加的问题

你的代码问题分析

你原来的代码存在两个问题:

  1. 循环语法错误:for i in len(df1) 中 len(df1) 是整数,无法被遍历,会触发 TypeError: 'int' object is not iterable。
  2. 判断逻辑错误:if i > 1 会漏掉df1长度为1的情况(比如你的示例数据),而你实际需要的是只要df1非空就追加。

正确实现方式

推荐方法:使用pd.concat(替代已弃用的append)

pandas的append方法已被标记为弃用,官方推荐用pd.concat来实现拼接,同时通过df1.empty判断df1是否为空:

import pandas as pd

# 仅当df1非空时,将df1追加到df2
if not df1.empty:
    df2 = pd.concat([df2, df1], ignore_index=True)
  • ignore_index=True:重置拼接后的索引,避免出现重复索引。

兼容写法:使用_append(不推荐长期使用)

如果习惯原append的写法,可使用pandas保留的_append方法(注意前面的下划线):

if not df1.empty:
    df2 = df2._append(df1, ignore_index=True)

示例执行结果

运行代码后,df2会更新为:

NameplaceAnimal
XyzLondoncheeta
TomParisdog
AbcChinaLion

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:27:25