【问题标题】:Returning differences between two columns in two different files in excel using python使用python返回excel中两个不同文件中两列之间的差异
【发布时间】:2020-05-21 20:05:23
【问题描述】:

我有两个 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

【问题讨论】:

  • 请提供示例输入和输出以制作minimal reproducible example
  • @G.Anderson 完成
  • 请使用您之前打开的问题进行澄清,而不是打开重复的问题
  • @G.Anderson 不幸的是它没有。这些选项仅在将它们添加到列的末尾时才会发现差异,但是这些值是随机添加的,因此如果将其随机添加到列中而不是末尾,则不会检测到

标签: python pandas csv concat difference


【解决方案1】:
# 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 的子集

【讨论】:

  • 您将如何打印差异以验证其是否有效?
  • 它仅检测位于列末尾的不同值。我有一个随机放置在其中一列中的值,它不会检测到它
  • 你能更好地给我解释一下这段代码吗?我输入的方式和你一样,但它不起作用
  • 如果你有其他列,那么你必须先按'名称'分组
  • 你也可以尝试'inner' join而不是outer,或者df1.set_index('Name'),或者给我更好的例子来说明你的文件和你的期望
【解决方案2】:

使用左侧的文件 2 进行左连接。之后,提取不匹配的 NaN 行。

【讨论】:

  • 你能把它写成脚本让我更好地理解它吗?
  • 我想得更好,我为您找到了更好的解决方案:dfDiff = pd.concat([df1, df2], axis = 0).drop_duplicates(keep = False)
【解决方案3】:

如果您只想检查一列,可以通过比较两个列表来尝试:

list1=df1['Name'].tolist()
list2=df2['Name'].tolist()
s = set(list1)
diff = [x for x in list2 if x not in s]

【讨论】:

  • 当不同的值位于列的末尾时,我只会得到列之间的差异。我在 file2 列中随机放置了一个值,但它没有检测到它。
猜你喜欢
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2020-10-12
  • 1970-01-01
相关资源
最近更新 更多