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

pandas DataFrame重排共有列顺序且保留非共有列的解决方案

pandas多DataFrame共有列顺序对齐方案

核心实现

以下代码可直接实现:共有列顺序完全对齐df1,同时保留df2全部独有列且维持原有相对顺序,无需手动指定列名:

df2 = df2[[col for col in df1.columns if col in df2.columns] + [col for col in df2.columns if col not in df1.columns]]

逻辑拆解

  1. 共有列提取:遍历df1的列,仅保留同时存在于df2的列,天然继承df1的列顺序
  2. 独有列提取:遍历df2原有列,仅保留不存在于df1的列,完全保留原有相对顺序
  3. 两部分列名列表拼接后直接对df2做列重排,无列丢失,百级到千级列量场景下性能无压力

大列量优化

如果列数超过5000列,可通过集合加速存在性判断:

df2_cols = set(df2.columns)
common_cols = [col for col in df1.columns if col in df2_cols]
unique_cols = [col for col in df2.columns if col not in common_cols]
df2 = df2[common_cols + unique_cols]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:06:04