在Python中合并两个不同的表

问题描述 投票:0回答:1

我对Python很陌生。 我正在尝试根据两个数据帧的共同“userID”合并两个数据帧:

*topUsersRating=topUsers.merge(ratings_df, left_on='userId', right_on='userId', how='inner')*

topUsers 中的“userId”类型被识别为一个对象(例如数字 75 显示为 :(75,)),因此,我收到此错误消息:

*You are trying to merge on object and int64 columns for key 'userId'. If you wish to proceed you should use pd.concat*

我尝试使用不同的方法将对象数据类型更改为 int 但它们不起作用。 谁能指导我如何解决这个问题?

python merge
1个回答
0
投票

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。希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.