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

如何拼接列名部分重叠、列数不同的DataFrame,缺失列填NaN?

解决方案

你需要使用pandas.concat()并保持默认的axis=0(上下拼接方向),传入实际的DataFrame对象而非字符串名称,配合ignore_index=True重置索引,就能自动对齐相同列名,额外列填充NaN。

核心代码

import pandas as pd

# 构造示例DataFrame
df1 = pd.DataFrame({'Column A': ['ID 1', 'ID 2'], 'Column B': ['Cell 2', 'Cell 4']})
df2 = pd.DataFrame({'Column A': ['ID 3', 'ID 4'], 'Column B': ['Cell 2', 'Cell 4'], 'ColumnC': ['info', 'info']})

# 执行上下拼接
result_df = pd.concat([df1, df2], ignore_index=True)
print(result_df)

输出结果

Column AColumn BColumnC
0ID 1Cell 2NaN
1ID 2Cell 4NaN
2ID 3Cell 2info
3ID 4Cell 4info

关键说明

  • 你之前错误传入了字符串['df1','df2'],需替换为实际的DataFrame变量[df1, df2]
  • axis=0是默认参数,无需额外指定,它会按行方向堆叠数据
  • ignore_index=True会重置结果的索引,避免出现重复的行索引
  • concat会自动对齐所有列名,仅存在于单个DataFrame的列,会用NaN填充缺失值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:16:24