python - 数据框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
给我加入和未加入的元素。我只想要未加入的元素。请问,我怎样才能得到渴望的元素?
解决方案
您可以将参数indicator=True
与外部连接一起使用,然后boolean indexing
使用Series.eq
for==
和Series.ne
for进行过滤!=
:
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
推荐阅读
- c# - getById 函数在存储库模式中采用一个或多个键
- html - 对 div 和图像的悬停效果在 css 中不起作用
- jenkins - Jenkins 中的配置全局安全性中缺少 JNLP 端口
- python - 替换“。” 使用 numpy 将十进制数写入文件时使用“,”
- apache-kafka - 处理来自 Kafka 的消息时避免数据丢失
- python - 设置 PyCharm 远程 conda 解释器
- java - SharedPreferences 返回错误值
- angular - 特定实体的大量动作/效果
- c# - 读取 ID 值始终为 0
- html - 如何让 z-index 工作,它拒绝打球