Want to find the difference between two outer-merge and inner-merge DataFrames, without finding any row with NaN
-- I want to keep some rows with them. Is there a way to do this using the difference
method or preferably without having to create both FrameA
and FrameB
?
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}])
DataA
a b
0 1 4
1 6 2
2 2 5
3 3 6
4 7 2
DataB
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')
FrameA
a b d
0 2 5 7
1 3 6 8
2 7 2 8
FrameB
a b d
0 1 4 NaN
1 6 2 NaN
2 2 5 7
3 3 6 8
4 7 2 8
Trying to find DataFrame differences...
list(FrameB.index.difference(FrameA.index))
Maybe you have a better solution, with this desired output:
a b d
0 1 4 NaN
1 6 2 NaN
You are looking for the 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.