【问题标题】:How to remove rows in a Pandas dataframe if the same row exists in another dataframe?如果同一行存在于另一个数据框中,如何删除 Pandas 数据框中的行?
【发布时间】:2017-11-26 03:38:01
【问题描述】:

我有两个数据框:

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

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

df_out = row1;row3

我怎样才能最有效地做到这一点?

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

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]

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以使用merge 和参数indicator 和外连接,query 进行过滤,然后使用drop 删除辅助列:

DataFrames 在所有列上连接,所以on 参数可以省略。

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

【讨论】:

    【解决方案2】:

    您可以将ab 转换为Indexs,然后使用Index.isin method 来确定哪些行是共同共享的:

    import pandas as pd
    a = pd.DataFrame({0:[1,2,3],1:[10,20,30]})
    b = pd.DataFrame({0:[0,1,2,3],1:[0,1,20,3]})
    
    a_index = a.set_index([0,1]).index
    b_index = b.set_index([0,1]).index
    mask = ~a_index.isin(b_index)
    result = a.loc[mask]
    print(result)
    

    产量

       0   1
    0  1  10
    2  3  30
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-21
      • 2019-06-10
      • 2020-10-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多