基于code列匹配对比两个数据集,提取差异记录
数据集匹配与差异记录提取方案
需求说明
- 遍历df1的每条code记录,仅处理在df2中存在的code
- 检查
count、length、width列数值是否一致,提取不一致的记录生成新数据集
示例数据集
df1
code count length width 13525 64 5 10 13456 20 10 20 13455 22 10 25 12334 10 2 5 12333 12 5 5 13234 18 8 10
df2
code count length width 13525 64 5 10 13456 20 10 22 13455 22 11 25 12334 10 2 5 13234 18 8 10
解决代码(基于Pandas)
import pandas as pd # 构造示例数据集 df1 = pd.DataFrame({ 'code': [13525, 13456, 13455, 12334, 12333, 13234], 'count': [64, 20, 22, 10, 12, 18], 'length': [5, 10, 10, 2, 5, 8], 'width': [10, 20, 25, 5, 5, 10] }) df2 = pd.DataFrame({ 'code': [13525, 13456, 13455, 12334, 13234], 'count': [64, 20, 22, 10, 18], 'length': [5, 10, 11, 2, 8], 'width': [10, 22, 25, 5, 10] }) # 1. 内连接合并,仅保留两边都存在的code记录 merged_df = pd.merge(df1, df2, on='code', suffixes=('_df1', '_df2')) # 2. 筛选目标列不一致的记录 diff_mask = (merged_df['count_df1'] != merged_df['count_df2']) | \ (merged_df['length_df1'] != merged_df['length_df2']) | \ (merged_df['width_df1'] != merged_df['width_df2']) # 3. 提取差异记录并整理格式 codes_that_dont_match = merged_df.loc[diff_mask, ['code', 'count_df2', 'length_df2', 'width_df2']] codes_that_dont_match.columns = ['code', 'count', 'length', 'width'] print(codes_that_dont_match)
输出结果
code count length width 1 13456 20 10 22 2 13455 22 11 25
关键步骤说明
- 内连接合并自动过滤掉df1中独有的
12333,无需额外处理 - 布尔掩码精准定位任意目标列数值不一致的记录
- 最后通过列重命名匹配期望的输出格式
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

