寻找合并(外部 - 内部)Pandas DF 差异

Finding Merge (Outer - Inner) Pandas DF differences

想要找到两个外部合并和内部合并 DataFrame 之间的区别,而不用 NaN 找到任何行——我想保留一些行。有没有办法使用 difference 方法或最好不必同时创建 FrameAFrameB?

import pandas as pd

DataA = pd.DataFrame([{"a": 1, "b": 4}, {"a": 6, "b": 2}, {"a": 2, "b": 5}, {"a": 3, "b": 6}, {"a": 7, "b": 2}])
DataB = pd.DataFrame([{"a": 2, "d": 7}, {"a": 7, "d": 8}, {"a": 3, "d": 8}])

数据A

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

数据B

    a   d
0   2   7
1   7   8
2   3   8

...

FrameA = pd.merge(DataA, DataB, on = "a", how ='inner')
FrameB = pd.merge(DataA, DataB, on = "a", how ='outer')

框架A

    a   b   d
0   2   5   7
1   3   6   8
2   7   2   8

帧B

    a   b   d
0   1   4   NaN
1   6   2   NaN
2   2   5   7
3   3   6   8
4   7   2   8

正在尝试找出 DataFrame 的差异...

list(FrameB.index.difference(FrameA.index))

也许您有更好的解决方案,具有以下所需的输出:

    a   b   d
0   1   4   NaN
1   6   2   NaN

您正在寻找 symmetric_difference:

a = DataA.set_index('a')
b = DataB.set_index('a')

# select rows from the outer join using the symmetric difference (^)
a.join(b, how='outer').loc[a.index ^ b.index].reset_index()