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

Pandas v2.1.0+:替代已弃用的空DataFrame.concat()的方案

优化Pandas 2.1.0+合并可能为空的DataFrame的方案

在Pandas 2.1.0及以上版本中,直接用pd.concat([df1, df2])合并可能为空的DataFrame会触发如下警告:

FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.

原有的多分支判断写法虽然能解决问题,但代码繁琐且扩展性差,以下是更优的解决方案:

方案1:筛选非空DataFrame后合并

# 收集所有非空的DataFrame
non_empty_dfs = [df for df in [df1, df2] if not df.empty]
# 合并非空DataFrame,若无有效数据则返回空DataFrame
result_df = pd.concat(non_empty_dfs) if non_empty_dfs else pd.DataFrame()

这种写法通过列表推导式先过滤掉空的DataFrame,只对有数据的对象执行concat,完全符合警告提示中“在concat前排除相关条目”的要求,既避免了警告,又简化了逻辑。如果后续需要合并更多DataFrame,只需在[df1, df2]列表中添加新对象即可,无需修改条件判断,扩展性更强。

方案2:一行简洁写法

如果追求代码紧凑,也可以压缩为一行:

result_df = pd.concat([df for df in [df1, df2] if not df.empty]) if any(not df.empty for df in [df1, df2]) else pd.DataFrame()

功能和方案1完全一致,适合喜欢精简代码的场景。

对比原方案

原有的if-elif多分支写法在仅合并两个DataFrame时还能应付,但当需要合并的DataFrame数量增加时,代码会变得冗长且难以维护;而筛选非空列表的写法逻辑统一,适配任意数量的DataFrame合并场景,代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:20:13