

新闻资讯
技术学院本文介绍如何通过pandas的merge操作精准识别两份客户数据中,以cust_id为键、town_id为追踪字段时发生变更的所有记录,并生成结构清晰的对比结果dataframe。
在数据分析和ETL流程中,常需比对两个时间点(如月初/月末、版本v1/v2)的客户主数据,快速定位关键字段(如所属区域town_id)是否发生变化。核心思路是:以主键(cust_id)为纽带合并两个DataFrame,再筛选出关联行中目标字段(town_id)值不一致的记录。
具体实现分三步:
完整代码如下:
import pandas as pd
# 示例数据
df1 = pd.DataFrame({
'name': ['cxa', 'cxb', 'cxc', 'cxd'],
'cust_id': ['c1001', 'c1002', 'c1003', 'c1004'],
'town_id': ['t001', 't001', 't001', 't002']
})
df2 = pd.DataFrame({
'name': ['cxa', 'cxb', 'cxd', 'cxe', 'cxf'],
'cust_id': ['c1001', 'c1002', 'c1004', 'c1005', 'c1006'],
'town_id': ['t002', 't001', 't001', 't
001', 't001']
})
# 执行变更检测
merged = df1.merge(df2, on="cust_id", how="inner", suffixes=("_initial", "_latter"))
changed = merged[merged["town_id_initial"] != merged["town_id_latter"]]
result = changed[["name_initial", "cust_id", "town_id_initial", "town_id_latter"]].rename(
columns={"name_initial": "name"}
)
print(result)输出结果:
name cust_id town_id_initial town_id_latter 0 cxa c1001 t001 t002 2 cxd c1004 t002 t001
⚠️ 注意事项:
该方法简洁、可读性强,是Pandas中处理键值变更分析的标准实践。