2024-04-29 06:05:03 发布
网友
如何区分两个数据帧中同名的to列? 我的意思是,我有一个列名为X的dataframe A和一个列名为X的dataframe B,如果我这样做pd.merge(A, B, on=['X']),我将得到A和B的公共X值,但是如何才能得到“非公共”值呢?
pd.merge(A, B, on=['X'])
如果将合并类型更改为how='outer'和indicator=True,则将添加一列来告诉您值是否为left/both/right only:
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列上筛选结果合并的df:
_merge
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中的值:
isin
In [5]: A[~A['x'].isin(B['x'])] Out[5]: x 0 0 1 1 2 2
如果将合并类型更改为
how='outer'
和indicator=True
,则将添加一列来告诉您值是否为left/both/right only:然后,您可以在
_merge
列上筛选结果合并的df:您还可以使用
isin
并对掩码求反,以查找不在B中的值:相关问题 更多 >
编程相关推荐