2017-06-22 189 views
2

我有两个dataframes:如果在另一个数据框中存在相同的行,如何删除Pandas数据框中的行?

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] 
+0

没有重复,因为我没有映射到两个数据框中的公共值的唯一标识。 – RRC

+0

不能标记它,但https://stackoverflow.com/questions/28901683/pandas-get-rows-which-are-not-in-other-dataframe – victor

回答

3

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

DataFrame加入所有列,所以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 
+0

太棒了!没有想到使用指标参数。解决我的问题。 – RRC

+1

很高兴能帮到你,美好的一天! – jezrael

0

你可以ab转化为Index S,然后使用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 
相关问题