我好像LEFT JOIN vs. LEFT OUTER JOIN in SQL Server和 https://chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/但还没有找到我要找的东西。我有两个 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
给我连接和未连接的元素。我只想要未连接的元素。请问,我怎样才能得到想要的元素?
最佳答案
您可以将参数 indicator=True
与外部连接一起使用,然后按 boolean indexing
进行过滤与 Series.eq
对于 ==
和 Series.ne
对于 !=
:
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
关于python - 外部加入数据框python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64024221/