我正在使用Pandas itertuples
方法在两个数据帧(df-A& df-B)之间执行行匹配。结果是df-B的副本,只有传递的结果。
df-B之前:
B Y
0 2 10
1 4 15
2 6 15
df-B之后(如df-B2):
B Y e
0 2 10 True
1 6 15 True
如何比较df-B和df-B2并仅返回缺失(隐含的假)行?
B Y
1 4 15
答案 0 :(得分:1)
使用~
进行掩码反转:
df-B[~df-B.e]
DataFrame.isin
的解决方案更为通用,因为它也会检查索引和列值。因此,列Y
设置为索引,然后获取掩码。上次使用boolean indexing
:
print (df1)
B Y
0 2 10
1 4 15
2 6 15
print (df2)
B Y e
0 2 10 True
2 6 15 True
df11 = df1.set_index('B')[['Y']]
df22 = df2.set_index('B')[['Y']]
mask = df11.isin(df22).reset_index()
print (mask)
B Y
0 2 True
1 4 False
2 6 True
print (df1[mask.Y])
B Y
0 2 10
2 6 15
print (df1[~mask.Y])
B Y
1 4 15
答案 1 :(得分:1)
这来自优秀的Pandas Cheat Sheet,我认为它会做你想做的事情:
pd.merge(df-B, df-B2, how='outer',
indicator=True)
.query('_merge == "left_only"')
.drop(['_merge'],axis=1)
这是一种获取df-B中未出现在df-B2中的行的方法。