嗯,一种方法是使用isin(但您也可以使用merge 命令来实现...我展示了这两种方法的示例)。例如:
>>> df1
A B C D
0 a b c d
1 e f g h
2 i j k l
3 m n o p
>>> df2
A B C D
0 a b c d
1 i j k l
>>> df1[~df1.isin(df2.to_dict('list')).all(axis=1)]
A B C D
1 e f g h
3 m n o p
解释。 isin 可以检查是否使用多列,如果你给它一个字典:
>>> df2.to_dict('list')
{'A': ['a', 'i'], 'C': ['c', 'k'], 'B': ['b', 'j'], 'D': ['d', 'l']}
然后isin 将创建一个布尔型 df,我可以使用它来选择我们想要的列(在这种情况下,需要所有列匹配,然后与 ~ 取反):
>>> df1.isin(df2.to_dict('list'))
A B C D
0 True True True True
1 False False False False
2 True True True True
3 False False False False
在具体示例中,我们不需要向isin 提供数据帧的dict 版本,因为我们只需查看A 列即可识别有效行:
>>> df1[~df1['A'].isin(df2['A'])]
A B C D
1 e f g h
3 m n o p
您也可以使用merge 执行此操作。在子集数据框中创建一个唯一列。合并时,较大数据框中的唯一行将为您创建的列具有 NaN:
>>> df2['test'] = 1
>>> new = df1.merge(df2,on=['A','B','C','D'],how='left')
>>> new
A B C D test
0 a b c d 1
1 e f g h NaN
2 i j k l 1
3 m n o p NaN
所以选择 test == NaN 的行并删除 test 列:
>>> new[new.test.isnull()].drop('test',axis=1)
A B C D
1 e f g h
3 m n o p
编辑:@user3654387 指出,合并方法对于大型数据帧的性能要好得多。