python - 外部加入数据框python

标签 python pandas dataframe

我好像LEFT JOIN vs. LEFT OUTER JOIN in SQL Serverhttps://chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/但还没有找到我要找的东西。我有两个 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对于 ==Series.ne对于 !=:

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

关于python - 外部加入数据框python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64024221/

相关文章:

python - 如何将数据框中的所有对象类型值转换为 int

r - r中的项目组合数

python - 为什么我无法使用python使用单个输入函数获得两个由空格分隔的整数

python - 无法在ansible模块中导入MySQLdb

python - 如何在 Python 中将 RGB 图像转换为灰度图像?

python - 具有多索引的 Groupby

python - 不平等加入 Pandas ?

python - Dataframe将数据类型写入txt文件

python - 获取包含负值的列的列名列表

python - 删除行和 ValueError 数组的长度不同