python - 根据2列找出2个pandas DataFrame的交集

标签 python pandas dataframe intersection

我会根据 2 列“x”和“y”找出 2 个 pandas DataFrame 的交集,并将它们组合成 1 个 DataFrame。数据是:

df[1]:
    x   y       id    fa
0   4   5  9283222   3.1
1   4   5  9283222   3.1
2  10  12  9224221   3.2
3   4   5  9284332   1.2
4   6   1    51249  11.2

df[2]:
    x   y        id   fa
0   4   5  19283222  1.1
1   9   3  39224221  5.2
2  10  12  29284332  6.2
3   6   1     51242  5.2
4   6   2     51241  9.2
5   1   1     51241  9.2

预期的输出类似于(可以忽略索引):

    x   y       id    fa
0   4   5  9283222   3.1
1   4   5  9283222   3.1
2  10  12  9224221   3.2
3   4   5  9284332   1.2
4   6   1    51249  11.2
0   4   5  19283222  1.1
2  10  12  29284332  6.2
3   6   1     51242  5.2

非常感谢!

最佳答案

你可以通过连接df1df2x,y列来找出交集,你可以用它来过滤 df1df2 通过 inner join,然后将两个结果与 pd.concat 连接起来应该可以满足您的需求:

intersection = df1[['x', 'y']].merge(df2[['x', 'y']]).drop_duplicates()
pd.concat([df1.merge(intersection), df2.merge(intersection)])

enter image description here

关于python - 根据2列找出2个pandas DataFrame的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529340/

相关文章:

r - 如何在 R 中命名 map_dfc() 的列?

python - pandas groupby 删除列

python - 你能帮我解决这个 SUDS/SOAP 问题吗?

python - 为什么 Azureml studio 处理 pip 包和 conda 包来创建环境而不是只有一个?

javascript - Braintree JSv3 payment_method_nonce 值与 HostedFields 不一致

python - pandas DataFrame 连接/更新 ("upsert")?

python - 如何使用 Pandas df 在 Python 中水平旋转 csv 表格?

python - python 中的 pandas 数据框以更有效的方式列出

python - Pandas :合并(内部连接)数据框的行数比原来的多

python - pyside-uic 在哪里?