如何在 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

查看:104
本文介绍了如何在 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']].

I would like to perform an anti-join so that the resulting data frame contains the rows of df1 where the key [['label1', 'label2']] is not found in df2.

生成的df应该是:

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

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

In R using dplyr, the code would be:

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

感谢您的帮助.

推荐答案

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

这篇关于如何在 pandas 中执行反联接或左外联接(获取数据集中所有不在另一行中的所有行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆