如何用Python Pandas对比两个Excel文件,输出变更与新增内容?
Pandas对比新旧CSV:识别新增、变更与停产条目
你之前的代码报错是因为直接按行位置对比列值,Pandas要求两个Series的索引/行数完全匹配才能这么做,但新旧文件的条目数量、顺序大概率不一样。核心解决思路是用Product作为唯一标识来关联数据,而不是硬按行比。
下面是完整的解决方案,能同时输出新增条目、内容变更条目和停产条目:
import pandas as pd # 读取新旧CSV,将Product设为索引(确保基于产品ID匹配,而非行位置) # 如果你的CSV是空格分隔,加上sep='\s+'避免列识别错误 old = pd.read_csv('old.csv', index_col='Product', sep='\s+') new = pd.read_csv('new.csv', index_col='Product', sep='\s+') # 全外连接合并两个表,用后缀区分新旧字段 merged = pd.merge( old, new, left_index=True, right_index=True, how='outer', suffixes=('_old', '_new') ) # 1. 提取新增条目:仅在新文件中存在的产品 new_items = merged[merged['Price_old'].isna()].dropna(axis=1) new_items.columns = ['Price', 'Description'] # 2. 提取停产条目:仅在旧文件中存在的产品 discontinued_items = merged[merged['Price_new'].isna()].dropna(axis=1) discontinued_items.columns = ['Price', 'Description'] # 3. 提取内容变更条目:产品存在于两个文件,但价格或描述有变化 change_mask = (merged['Price_old'] != merged['Price_new']) | (merged['Description_old'] != merged['Description_new']) changed_items = merged[change_mask].dropna(subset=['Price_old', 'Price_new']) # 整理成最新的字段格式 changed_items = changed_items[['Price_new', 'Description_new']].rename( columns={'Price_new': 'Price', 'Description_new': 'Description'} ) # 输出结果 print("=== 新增产品 ===") print(new_items) print("\n=== 内容变更产品 ===") print(changed_items) print("\n=== 停产产品 ===") print(discontinued_items)
代码说明:
index_col='Product':把产品ID设为索引,确保合并时是按产品匹配,而非行的位置。how='outer':全外连接会保留新旧文件的所有条目,不存在的字段用NaN填充,方便后续判断。- 通过
isna()筛选出仅存在于某一个文件的条目,标记为新增/停产。 - 用
change_mask掩码筛选出价格或描述有差异的条目,即为内容变更。
针对你的示例数据,运行后输出:
=== 新增产品 === Price Description Product 4 4.25 Product 4 === 内容变更产品 === Price Description Product 3 3.50 Product 3 === 停产产品 === Price Description Product 2 2.25 Product 2
完全符合你要的结果,同时还输出了停产的Product2。
内容的提问来源于stack exchange,提问作者vetcode
相关产品推荐
相关产品推荐

