我有两个csv文件,它们的公用列名为“名称”。文件2将不断更新并在列中随机添加新值。我如何编写一个脚本来比较两列并查找差异,而不管新值在file2中的位置。
仅当新值在列的末尾而不是在列中随机出现时,其他解决方案才会发现差异。
我尝试过的代码(仅在列底部输出新值,而不是在列中随机输出新值):
df1 = pd.read_csv('file1.csv')
df2 = pd.read_csv('file2.csv')
new_df = (df1[['Name']].merge(df2[['Name']],on='Name',how = 'outer',indicator = True)
.query("_merge != 'both'")
.drop('_merge',axis = 1))
new_df.to_csv('file4.csv')
文件1:
Name
gfd454
3v4fd
th678iy
文件2:
Name
gfd454
fght45
3v4fd
th678iy
输出应为:
Name
fght45
最佳答案
# df1 original dataframe of File_1 data
df1 = pd.DataFrame({'Name':[ 'gfd454' , '3v4fd', 'th678iy']})
# df2 dataframe of changing File_2 data
df2 = pd.DataFrame({'Name':[ 'gfd454' , 'abcde', 'fght45', '3v4fd', 'abcde' ,'th678iy', 'abcde']})
# Assuming df1 comprises distinct elements and doesn't change, and that
# df2 contains all elements of df1 and more (the new updates)
# df2 may have duplicates like 'abcde'
# Drop duplicates in df2, if df1 has duplicates also drop it first
# ``keep = first`` : Drop duplicates except for the first occurrence.
df2.drop_duplicates(keep='first', inplace=True)
print(df2)
# pandas.concat adds elements of df2 to df1, even if it already exists in df1
df_concat = pd.concat([df1,df2], join='outer', ignore_index = True)
print(df_concat)
# now drop the duplicates between df1, df2
df_diff = df_concat .drop_duplicates(keep=False)
print(df_diff)
现在,问题在于您必须确保df1-df2 = {},
即df1是df2的子集
关于python - 使用Python在Excel中返回两个不同文件中两列之间的差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60083748/