[英]Outer Join on dataframes python
我似乎在 SQL 服務器和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] 不是。
我希望它具有一個 dataframe 的所有值,但不加入另一個 dataframe。例如:
A some_left_outer_join B = C
C = pd.DataFrame(np.array([ [4, 5, 6], [4, 5, 6]]),
columns=['a', 'b', 'c'])
並從兩個數據幀中獲取所有不加入另一個 dataframe 的值。例如:
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
與外部連接一起使用,然后使用Series.eq
為==
和Series.ne
為!=
的boolean indexing
進行過濾:
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
一個技巧是向 A 和 B 添加虛擬列。因此在不匹配的行中,您將在虛擬列中獲得 NaN。 您可以稍后刪除虛擬列
B['d'] = 0
A['e'] = 0
AB = pd.merge(left=A, right=B, how='outer', on=['a', 'b', 'c'])
C = AB[AB.d.apply(pd.isnull)]
D = AB[(AB.d.apply(pd.isnull)) | (AB.e.apply(pd.isnull))]
C
a b c e d
4 4 5 6 0.0 NaN
5 4 5 6 0.0 NaN
D
a b c e d
4 4 5 6 0.0 NaN
5 4 5 6 0.0 NaN
6 9 8 7 NaN 0.0
7 9 8 7 NaN 0.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.