gpt4 book ai didi

python - Pandas (Python)中的 "Anti-merge"

转载 作者:太空狗 更新时间:2023-10-29 17:12:35 26 4
gpt4 key购买 nike

如何找出两个数据框中同名列之间的区别?我的意思是我的数据框 A 有一个名为 X 的列,数据框 B 有一个名为 X 的列,如果我执行 pd.merge(A, B, on=['X']),我会得到A 和 B 的共同 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

关于python - Pandas (Python)中的 "Anti-merge",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38242368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com