首页 > 解决方案 > 数据框python上的外部连接

问题描述

我似乎在 SQL Server和https://chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/中看到了LEFT JOIN 与 LEFT OUTER JOIN,但还没有找到我想要的东西。我有两个 python 数据框:

A = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]]),
                   columns=['a', 'b', 'c'])

    a   b   c
0   1   2   3
1   4   5   6
2   1   2   3
3   4   5   6

B = pd.DataFrame(np.array([[7, 8, 9], [7, 8, 9], [3, 2, 1], [3, 2, 1]]),
                   columns=['c', 'b', 'a'])

    c   b   a
0   7   8   9
1   7   8   9
2   3   2   1
3   3   2   1

其中值 [1, 2, 3] 在两者中都重复,但 [4, 5, 6] 和 [9, 8, 7] 不是。

我希望它具有来自一个数据帧但不加入另一个数据帧的所有值。例如:

A some_left_outer_join B = C

C = pd.DataFrame(np.array([ [4, 5, 6], [4, 5, 6]]),
                   columns=['a', 'b', 'c'])

并拥有两个数据帧中不加入另一个数据帧的所有值。例如:

A some_outer_join B = D

D = pd.DataFrame(np.array([ [4, 5, 6], [4, 5, 6] , [9, 8, 7] , [9, 8, 7]]),
                   columns=['a', 'b', 'c'])

 (pd.merge(left=A, right=B, how='left', on=['a', 'b', 'c']))

    a   b   c
0   1   2   3
1   1   2   3
2   4   5   6
3   1   2   3
4   1   2   3
5   4   5   6

给我加入和未加入的元素。我只想要未加入的元素。请问,我怎样才能得到渴望的元素?

标签: pythonpandasdataframe

解决方案


您可以将参数indicator=True与外部连接一起使用,然后boolean indexing使用Series.eqfor==Series.nefor进行过滤!=

df = (pd.merge(left=A, right=B, how='outer', on=['a', 'b', 'c'], indicator=True))
print (df)
   a  b  c      _merge
0  1  2  3        both
1  1  2  3        both
2  1  2  3        both
3  1  2  3        both
4  4  5  6   left_only
5  4  5  6   left_only
6  9  8  7  right_only
7  9  8  7  right_only

C = df[df['_merge'].eq('left_only')]
print (C)
   a  b  c     _merge
4  4  5  6  left_only
5  4  5  6  left_only

D = df[df['_merge'].ne('both')]
print (D)
   a  b  c      _merge
4  4  5  6   left_only
5  4  5  6   left_only
6  9  8  7  right_only
7  9  8  7  right_only

如果还想删除列:

s = df.pop('_merge')
C = df[s.eq('left_only')]
print (C)
   a  b  c
4  4  5  6
5  4  5  6

D = df[s.ne('both')]
print (D)
   a  b  c
4  4  5  6
5  4  5  6
6  9  8  7
7  9  8  7

推荐阅读