Python跨表查找数据:未找到时复制到新文件的代码问题排查
问题
我是编程新手,正在学习使用Python处理数据。我需要对比两个数据相似的Excel文件,找出df1中「concatenate」列里不存在于df2同列的行,并将这些行复制到新文件,以此发现文件更新后的变化。但我复制了两个完全相同的输入文件,本应得到空的输出文件,却仍有数据被写入,现有代码如下:
import pandas as pd # load the data from the two files into Pandas dataframes df1 = pd.read_excel('/Users/bjoern/Desktop/PythonProjects/Comparison/MergedKeepa_2023-02-05.xlsx') df2 = pd.read_excel('/Users/bjoern/Desktop/PythonProjects/Comparison/MergedKeepa_2023-02-04.xlsx') # extract the values from column Concatenate in both dataframes col_a_df1 = df1['concatenate'] col_a_df2 = df2['concatenate'] # find the intersection of the values in column A of both dataframes intersection = col_a_df1.isin(col_a_df2) # filter the rows of df1 where the value in column A is not found in df2 df1 = df1[intersection] # write the filtered data to a new Excel file df1.to_excel('/Users/bjoern/Desktop/PythonProjects/Comparison/filtered_data.xlsx', index=False)
请问我哪里出错了?
问题分析与修正
你的代码逻辑完全搞反了:
col_a_df1.isin(col_a_df2)返回的是df1中「concatenate」列存在于df2同列的行的布尔标记,你用这个过滤后,保留的是两个文件共有的行——因为你用的是完全相同的文件,所以所有行都被保留,自然输出文件有数据。- 你要找的是df1中不存在于df2的行,需要对这个布尔序列取反,用
~操作符即可。
修正后的代码:
import pandas as pd # 读取两个Excel文件 df1 = pd.read_excel('/Users/bjoern/Desktop/PythonProjects/Comparison/MergedKeepa_2023-02-05.xlsx') df2 = pd.read_excel('/Users/bjoern/Desktop/PythonProjects/Comparison/MergedKeepa_2023-02-04.xlsx') # 筛选df1中concatenate列不在df2同列的行 filtered_df = df1[~df1['concatenate'].isin(df2['concatenate'])] # 将结果写入新Excel文件 filtered_df.to_excel('/Users/bjoern/Desktop/PythonProjects/Comparison/filtered_data.xlsx', index=False)
如果修正后仍有异常,检查两列的数据类型是否一致(比如存在字符串与数字混合、空值NaN等情况),可以用df['concatenate'].dtype查看数据类型,必要时先统一类型再做对比。
内容的提问来源于stack exchange,提问作者bocki
相关产品推荐
相关产品推荐

