识别不在另一个数据框中的记录 [英] Identify records NOT in another dataframe

查看:49
本文介绍了识别不在另一个数据框中的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I have one dataframe like this:

data1 = pd.DataFrame([['a','z',0],['a','y',20],['b','z',1]],columns=['id1','id2','number'])
data2 = pd.DataFrame([['a','y',1],['a','y',1],['b','z',0]],columns=['id1','id2','number'])

我想返回data1而不是data2中的记录(由id1和id2连接).

I want to return the records that are in data1 and not data2 (as joined by id1 and id2).

在这种情况下,我只希望它返回一个记录['a','z',0],因为['a','y']和['b','z']都存在在data2中.

In this case, I would just want it to return one record ['a','z',0] since both ['a','y'] and ['b','z'] do exist in data2.

推荐答案

我认为还有另一种方法.如果我们将两列都设置为索引,则可以使用.isin方法过滤出所需内容:

I think there is an alternative way. If we set both columns as index we can use .isin method to filter out what's needed:

data1.set_index(['id1', 'id2'], inplace=True)
data2.set_index(['id1', 'id2'], inplace=True)
data1[~data1.index.isin(data2.index)].reset_index()

收益:

  id1 id2  number
0   a   z       0

无论您在number中拥有什么.

这篇关于识别不在另一个数据框中的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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