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

56

我有一个数据框A dfA,像这样:

enter image description here

还有另一个数据框B dfB,它长这样:

enter image description here

我想在dfA中增加一个名为“存在”的列,如果用户和电影都存在于dfB中,则为'True',否则为'False'。 因此,dfA应该变成这样:

enter image description here


17
请勿使用PNG格式作为数据或表格的格式,应该使用文本格式。 - Merlin
1个回答

68
你可以使用带有参数indicatormerge,然后删除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

有必要指出 OP 的目标需要进行左外连接。更多细节请参见:https://realpython.com/pandas-merge-join-and-concat/#how-to-merge - Hari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接