Ido*_*odo 3 python join dataframe python-3.x pandas
我有两个相同列的dfA和dfB数据帧.我希望只获取dataframe dfB中不存在于dataframe dfA中的记录.
要清楚,我不想在dfA中获取不在dfB中的记录.
我设法破解了一起使用它的东西,但代码不容易理解,而且扩展不是非常pythonic.
我正在寻找一个更优雅的解决方案,也许使用pandas join/merge/append但是无法使其工作.
我想要的例子:
dfA:
Date Category Price
1 2013-11-24 Coat 22.1
2 2013-11-24 Shirt 8.7
3 2013-11-01 Socks 9 <<< Only present in this df
dfB:
Date Category Price
1 2013-11-24 Coat 22.1
2 2013-11-24 Shirt 8.7
3 2013-11-24 Helmet 2.1 <<< Only present in this df
4 2013-11-24 Pants 10.7 <<< Only present in this df
Result:
Date Category Price
1 2013-11-24 Helmet 2.1
2 2013-11-24 Pants 10.7
Run Code Online (Sandbox Code Playgroud)
其中一种惯用方法是使用merge(..., how='outer', indicator=True)和按生成的列过滤生成的DF _merge:
In [18]: (A.merge(B, how='outer', indicator=True)
.query("_merge == 'right_only'")
.drop('_merge',1))
Out[18]:
Date Category Price
3 2013-11-24 Helmet 2.1
4 2013-11-24 Pants 10.7
Run Code Online (Sandbox Code Playgroud)