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

编程入门 行业动态 更新时间:2024-10-25 16:21:40
本文介绍了如何在 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"))

感谢您的帮助.

推荐答案

将isin与tuple

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 中执行反联接或左外联接(获取数据集中所有不在另一行中的所有行)

本文发布于:2023-10-18 03:20:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502923.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:外联   数据   如何在   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!