python - 检查一个数据框中的一行是否存在于另一个数据框中

标签 python pandas dataframe

我有一个这样的数据框A:

enter image description here

另一个数据框 B 看起来像这样:

enter image description here

我想向数据框 A 添加一列“存在”,这样如果用户和电影都存在于数据框 B 中,则“存在”为 True,否则为 False。 所以A应该变成这样: enter image description here

最佳答案

您可以使用 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

关于python - 检查一个数据框中的一行是否存在于另一个数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38855204/

相关文章:

python - 创建复杂的条件列(几何平均数)Python

python - 连接 DataFrame,但仅保留一列

python - 如何在一行 python pandas 代码中应用 2 个不同的条件?

python - 重命名 Panda Series/DataFrame 的索引

python - 将 Pandas 数据框转换为唯一元组列表

python - 循环并制作新列python

python - 带参数的 Django ManyToManyField 过滤器?

python - 删除 numpy 语句中的 for 循环

python - git-python 从存储库获取提交提要

python - 如何读取逗号旁边有双引号的 csv 文件