熊猫中的“反合并”(Python)
如何在两个数据框中找出同名列之间的区别?我的意思是,我有一个名为X的数据框A和一个名为X的数据框B,如果这样做的话pd.merge(A, B,
on=['X'])
,我将获得A和B的通用X值,但是我如何获得“非通用”的X值?
-
如果将合并类型更改为
how='outer'
,indicator=True
这将添加一列以告诉您这些值是否仅是左/左右/右:In [2]: A = pd.DataFrame({'x':np.arange(5)}) B = pd.DataFrame({'x':np.arange(3,8)}) print(A) print(B) x 0 0 1 1 2 2 3 3 4 4 x 0 3 1 4 2 5 3 6 4 7 In [3]: pd.merge(A,B, how='outer', indicator=True) Out[3]: x _merge 0 0.0 left_only 1 1.0 left_only 2 2.0 left_only 3 3.0 both 4 4.0 both 5 5.0 right_only 6 6.0 right_only 7 7.0 right_only
然后,您可以在
_merge
col上过滤结果合并的df :In [4]: merged = pd.merge(A,B, how='outer', indicator=True) merged[merged['_merge'] == 'left_only'] Out[4]: x _merge 0 0.0 left_only 1 1.0 left_only 2 2.0 left_only
您也可以使用
isin
和否定掩码以查找不在B中的值:In [5]: A[~A['x'].isin(B['x'])] Out[5]: x 0 0 1 1 2 2