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

如何仅将DataFrame中ID未存在于另一DataFrame的行移动或追加?

解决方法:将Staging中未存在的ID行追加到Permanent DataFrame

嘿,这个需求在日常数据同步场景里太常见了!用pandas就能轻松实现,我给你拆解成核心步骤,再附上代码示例,一看就明白~

核心逻辑

要实现这个需求,其实就两步:

  1. 从Staging里筛选出ID未出现在Permanent中的行
  2. 把这些筛选出来的新行追加到Permanent里,得到更新后的全量数据

具体实现(附示例)

先模拟你提到的场景数据,再给两种常用的实现方法:

模拟示例数据

假设你的两个DataFrame长这样:

import pandas as pd

# Staging:每日导入的新数据
staging = pd.DataFrame({
    'ID': [1, 2, 3],
    'Value': ['A', 'B', 'C']
})

# Permanent:留存所有历史记录的全量数据
permanent = pd.DataFrame({
    'ID': [1, 4],
    'Value': ['A', 'D']
})

方法一:用isin()快速筛选(最直观)

这是最简单直接的方法,适合仅用ID判断的场景:

# 1. 筛选Staging中ID不在Permanent里的行
# ~ 符号表示取反,也就是"不在"的意思
new_rows = staging[~staging['ID'].isin(permanent['ID'])]

# 2. 追加到Permanent,ignore_index=True重置索引避免冲突
updated_permanent = pd.concat([permanent, new_rows], ignore_index=True)

# 输出结果
print(updated_permanent)

运行后你会得到想要的更新后的Permanent:

ID Value
0   1     A
1   4     D
2   2     B
3   3     C

方法二:用merge找差异行(适合复杂匹配场景)

如果你的匹配条件不只是ID(比如需要多列共同判断),用merge方法会更灵活:

# 1. 用左连接对比两个DataFrame,标记行的来源
merged = staging.merge(permanent, on='ID', how='left', indicator=True)

# 2. 筛选出仅在Staging中存在的行,去掉标记列
new_rows = merged[merged['_merge'] == 'left_only'].drop(columns='_merge')

# 3. 追加到Permanent
updated_permanent = pd.concat([permanent, new_rows], ignore_index=True)

注意事项

  • 确保ID列的数据类型一致!如果一个是整数、一个是字符串,isin()会判断错误,可提前用staging['ID'] = staging['ID'].astype(str)统一类型
  • 如果Permanent里可能存在重复ID,拼接后可以用updated_permanent = updated_permanent.drop_duplicates(subset='ID', keep='first')去重
  • 新版本pandas已经弃用了append()方法,所以推荐用pd.concat()来拼接DataFrame

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:49:52