gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:25:54 25 4
gpt4 key购买 nike

我会根据 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com