如何在 pandas 中执行反连接或左外连接(根据多个键获取数据集中不在另一个数据集中的所有行)

How to perform an anti-join, or left outer join, (get all the rows in a dataset which are not in another based on multiple keys) in pandas

我有两个数据集:

df1 = pd.DataFrame(data = {'label1': ['A', 'A', 'B', 'C'], 'label2': ['a', 'b', 'c', 'd'], 'value': [1,2,3,4]})

df2 = pd.DataFrame(data = {'label1': ['A', 'A', 'D', 'E'], 'label'2': ['a', 'd', 'c','e'], 'value2': [10,12,23,14]})

我想执行反连接,以便生成的数据帧包含 df1 的行,其中在 df2 中找不到键 [['label1', 'label2']]。

生成的 df 应该是:

label1     label2     value
A          b          2
B          c          3
C          d          4

在使用 dplyr 的 R 中,代码为:

df3 = anti_join(df1, df2, by = c("label1", "label2"))

感谢您的帮助。

选项 1

只需执行内部联接并从 df1 中删除相交的行。

df1.drop(df1.merge(df2).index)

选项2:

您需要执行左联接并查看有多少行对于来自 df2 的列显示为空。

mer = df1.merge(df2, how='left')
mer[mer['value2'].isnull()].drop(['value2'], 1)

输出:

  label1    label2  value
1   A          b    2
2   B          c    3
3   C          d    4

使用 isintuple

df1[~df1[['label1','label2']].apply(tuple,1).isin(df2[['label1','label2']].apply(tuple,1))]
Out[140]: 
  label1 label2  value
1      A      b      2
2      B      c      3
3      C      d      4