【问题标题】:Compare two datafarmes in two columns and get the difference比较两列中的两个数据场并获得差异
【发布时间】:2023-03-19 16:34:02
【问题描述】:

假设我有一个像这样的数据框:

df1:
     col1          col2
0    data1         math
1    data1         math2
2    data2         math
3    data3         math
4    data4         math2

df2:
     col1          col2
0    data1         math
1    data1         math2
2    data1         math3
3    data2         math2
4    data3         math
5    data4         math2
6    data4         math3

如何根据 col1 和 col2 比较这两个数据帧并获得差异(删除与 df1 匹配的所有行)并拥有这样的数据帧:

     col1          col2
0    data1         math3
1    data2         math2
2    data4         math3

我试过这个,但它不起作用:

df3 = df2[~(df2['col2'].isin(df1['col2']))].reset_index(drop=True)

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    您可以与indicator=True 执行合并,并只保留right_only 行:

    (df1.merge(df2, on=['col1', 'col2'], how='outer', indicator=True)
        .query('_merge == "right_only"')
        .drop(columns='_merge').reset_index(drop=True)
    )
    

    输出:

        col1   col2
    0  data1  math3
    1  data2  math2
    2  data4  math3
    

    【讨论】:

      【解决方案2】:

      您的解决方案应该通过比较 MultiIndex 或元组来更改:

      df3 = df2[~df2.set_index(['col1','col2']).index.isin(df1.set_index(['col1','col2']).index)].reset_index(drop=True)
      
      df3 = df2[~df2[['col1','col2']].apply(tuple, 1).isin(df1[['col1','col2']].apply(tuple, 1))].reset_index(drop=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 2020-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多