如何对比两个Pandas DataFrame差异及解决标签匹配报错
报错原因
ValueError: Can only compare identically-labeled Series objects 报错的核心原因是你要对比的两个
Project ID序列长度不同(两个表行数不一致),同时pandas默认会按索引对齐后再做比较,两个表的索引也不匹配,因此无法直接逐行对比。
解决方法
你需要以Project ID作为唯一主键做两个表的关联,再对比其他字段的差异,根据你的需求可以选择以下两种处理方案:
方案1:找出仅存在于单个表的项目(缺失的项目)
用pandas的merge做外连接,搭配indicator参数标记数据来源,就能快速定位哪个表多了项目、哪个表少了项目:
import pandas as pd # 读取两个csv文件 df1 = pd.read_csv('C:/Users/Text/Downloads/D1.csv') df2 = pd.read_csv('C:/Users/Text/Downloads/D2.csv') # 以Project ID为键做外连接,标记数据来源 diff_df = df1.merge(df2, on='Project ID', how='outer', suffixes=('_df1', '_df2'), indicator=True) # 筛选出仅在单个表存在的项目 only_in_df1 = diff_df[diff_df['_merge'] == 'left_only'] only_in_df2 = diff_df[diff_df['_merge'] == 'right_only'] print("只在D1中存在的项目:") print(only_in_df1) print("\n只在D2中存在的项目:") print(only_in_df2)
方案2:对比两表共有的项目的字段差异
如果两个表都存在的同Project ID项目,需要校验Price、Project Description字段是否有差异,可以在上面外连接的基础上新增对比逻辑:
# 筛选出两个表都存在的项目 both_exist = diff_df[diff_df['_merge'] == 'both'].copy() # 对比价格和项目描述的差异 both_exist['price_diff'] = both_exist['Price_df1'] != both_exist['Price_df2'] both_exist['desc_diff'] = both_exist['Project Description_df1'] != both_exist['Project Description_df2'] # 筛选出存在字段差异的项目 field_diff = both_exist[(both_exist['price_diff'] == True) | (both_exist['desc_diff'] == True)] print("\n两个表都存在,但字段有差异的项目:") print(field_diff)
注意事项
- 如果
Project ID存在空值,建议先调用dropna(subset=['Project ID'])清除空值行再对比,避免结果出现干扰 - 文本字段对比如果需要忽略大小写、前后空格,可以先做预处理,比如
df['Project Description'] = df['Project Description'].str.strip().str.lower()再执行对比
内容的提问来源于stack exchange,提问作者MDL7833
相关产品推荐
相关产品推荐

