pandas 如何获得两个数据帧的交集?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29289143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:06:38  来源:igfitidea点击:

How to get the intersection of two dataframes?

pythonpandasdataframe

提问by theQman

I have two dataframes of similar format:

我有两个类似格式的数据框:

df1 = DataFrame({'a':[0,1,2,3,4], 'b':['q','r','s','t','u']})
df1

    a   b
0   0   q
1   1   r
2   2   s
3   3   t
4   4   u

df2 = DataFrame({'a':[4,3,2,1,999], 'b':['u','r','s','t','u']})
df2

    a   b
0   4   u
1   3   r
2   2   s
3   1   t
4   999 u

I would like to get a new dataframe that has rows that appear in both of these (ignoring the index). So the above example gives a dataframe

我想获得一个新的数据框,其中的行出现在这两个中(忽略索引)。所以上面的例子给出了一个数据框

    a   b
0   4   u
1   2   s

How do I get this intersection?

我如何得到这个交叉点?

回答by EdChum

You can just perform a merge, this will use all columns and the default type of merge is innerso values must be present in both dfs:

您可以只执行 a merge,这将使用所有列,并且默认的合并类型是inner这样的值必须存在于两个 dfs 中:

In [71]:

df1.merge(df2)
Out[71]:
   a  b
0  2  s
1  4  u