根据2列找出2 pandas DataFrame的交集
Find out intersection of 2 pandas DataFrame according to 2 columns
我想根据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
非常感谢!
您可以通过连接 df1
和 df2
中的 x,y
列来找出交集,您可以通过它过滤 df1
和 df2
内部联接,然后将两个结果与 pd.concat
连接起来应该可以满足您的需要:
intersection = df1[['x', 'y']].merge(df2[['x', 'y']]).drop_duplicates()
pd.concat([df1.merge(intersection), df2.merge(intersection)])
最简单的解决方案:
df1.columns.intersection(df2.columns)
我想根据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
非常感谢!
您可以通过连接 df1
和 df2
中的 x,y
列来找出交集,您可以通过它过滤 df1
和 df2
内部联接,然后将两个结果与 pd.concat
连接起来应该可以满足您的需要:
intersection = df1[['x', 'y']].merge(df2[['x', 'y']]).drop_duplicates()
pd.concat([df1.merge(intersection), df2.merge(intersection)])
最简单的解决方案:
df1.columns.intersection(df2.columns)