我正在尝试根据两个数据框的共同“userID”合并两个数据框:
topUsersRating=topUsers.merge(ratings_df, left_on='userId', right_on='userId', how='inner')
topUsers 中的“userId”类型被识别为一个对象(例如数字 75 显示为
(75,)
),因此,我收到以下错误消息:
您正在尝试合并键“userId”的对象和 int64 列。如果您想继续,您应该使用 pd.concat
我尝试使用不同的方法将对象数据类型更改为 int,但没有成功。
如何解决这个问题?
topUsers DataFrame 中的“userId”似乎被识别为元组(例如,(75,))而不是整数。这就是为什么您在尝试将其与 ratings_df 合并时收到错误,其中“userId”是一个整数。
您可以通过从元组中提取第一个元素来将 topUsers 中的“userId”转换为整数。具体方法如下:
# Convert 'userId' from tuple to int
topUsers['userId'] = topUsers['userId'].apply(lambda x: x[0] if isinstance(x, tuple) else x)
# Now you can merge
topUsersRating = topUsers.merge(ratings_df, left_on='userId', right_on='userId', how='inner')
此代码检查每个“userId”是否是一个元组,如果是,则用其第一个元素替换该元组。完成此转换后,您应该能够毫无问题地合并两个 DataFrame。
您可以尝试使用
astype
将数据框列转换为所需的数据类型
topUsers['userId'] = topUsers['userId'].astype('int64')
转换列的数据类型后,您可以执行合并。