pandas 检查一个数据框中的一行是否存在于另一个数据框中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38855204/
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
Check if a row in one data frame exist in another data frame
提问by HimanAB
I have a data frame A like this:
我有一个像这样的数据框 A:
And another data frame B which looks like this:
另一个数据框 B 如下所示:
I want to add a column 'Exist' to data frame A so that if User and Movie both exist in data frame B then 'Exist' is True, otherwise it is False.
So A should become like this:
我想向数据框 A 添加一列“存在”,以便如果用户和电影都存在于数据框 B 中,则“存在”为真,否则为假。所以A应该变成这样:
回答by jezrael
You can use merge
with parameter indicator
, then remove column Rating
and use numpy.where
:
您可以使用merge
参数indicator
,然后删除列Rating
并使用numpy.where
:
df = pd.merge(df1, df2, on=['User','Movie'], how='left', indicator='Exist')
df.drop('Rating', inplace=True, axis=1)
df['Exist'] = np.where(df.Exist == 'both', True, False)
print (df)
User Movie Exist
0 1 333 False
1 1 1193 True
2 1 3 False
3 2 433 False
4 3 54 True
5 3 343 False
6 3 76 True