如果同一行存在于另一个数据框中,如何删除Pandas数据框中的行? [英] How to remove rows in a Pandas dataframe if the same row exists in another dataframe?

查看:104
本文介绍了如果同一行存在于另一个数据框中,如何删除Pandas数据框中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框:

 df1 = row1;row2;row3
 df2 = row4;row5;row6;row2

我希望我的输出数据框仅包含df1中唯一的行,即:

I want my output dataframe to only contain the rows unique in df1, i.e.:

df_out = row1;row3

如何最有效地获取此信息?

How do I get this most efficiently?

这段代码可以实现我想要的,但是使用了2个for循环:

This code does what I want, but using 2 for-loops:

a = pd.DataFrame({0:[1,2,3],1:[10,20,30]})
b = pd.DataFrame({0:[0,1,2,3],1:[0,1,20,3]})

match_ident = []
for i in range(0,len(a)):
    found=False
    for j in range(0,len(b)):
        if a[0][i]==b[0][j]:
            if a[1][i]==b[1][j]:
                found=True
    match_ident.append(not(found))

a = a[match_ident]

推荐答案

您正在使用 merge ,带有参数indicator和外部联接,

You an use merge with parameter indicator and outer join, query for filtering and then remove helper column with drop:

DataFrames连接到所有列,因此可以省略on参数.

DataFrames are joined on all columns, so on parameter can be omit.

print (pd.merge(a,b, indicator=True, how='outer')
         .query('_merge=="left_only"')
         .drop('_merge', axis=1))
   0   1
0  1  10
2  3  30

这篇关于如果同一行存在于另一个数据框中,如何删除Pandas数据框中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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