如果Pandas数据框中的行存在于另一个数据框中,如何删除该数据框中的行?

2024-05-21 02:43:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧:

 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]

Tags: 数据indataframeforlenifmatchrange
2条回答

您可以使用带参数indicator^{}和外部联接,^{}进行筛选,然后使用^{}删除助手列:

所有列上都联接了数据帧,因此可以省略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

您可以将ab转换为Indexs,然后使用^{} 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

相关问题 更多 >