首页 > 解决方案 > 合并具有相同行数的 2 个数据帧时出现值错误

问题描述

我有一个这样的数据框:

+-----+-------+---------+
|  id | Time  | Name    |
+-----+-------+---------+
| 1   | 1     | John    |
+-----+-------+---------+
| 2   | 2     | David   |
+-----+-------+---------+
| 3   | 4     | Rebecca |
+-----+-------+---------+
| 4   | later | Taylor  |
+-----+-------+---------+
| 5   | later | Li      |
+-----+-------+---------+
| 6   | 8     | Maria   |
+-----+-------+---------+

我想根据“id”和时间与另一个表合并:

  data1=pd.merge(data1, data2,left_on=['id', 'time'],right_on=['id', 'time'], how='left')

其他表数据

+-----+-------+--------------+
|  id | Time  | Job          |
+-----+-------+--------------+
| 2   | 2     | Doctor       |
+-----+-------+--------------+
| 1   | 1     | Engineer     |
+-----+-------+--------------+
| 4   | later | Receptionist |
+-----+-------+--------------+
| 3   | 4     | Professor    |
+-----+-------+--------------+
| 5   | later | Lawyer       |
+-----+-------+--------------+
| 6   | 8     | Trainer      |
+-----+-------+--------------+


它引发了错误:

ValueError: You are trying to merge on int64 and object columns. If you wish to proceed you should use pd.concat

我尝试了什么:

data1['time']=data1['time'].astype(str)
data2['time']=data2['time'].astype(str)

不工作。我能做些什么?PS:在这个例子中 Id 不同,但在我的数据中 Id 可以是相同的,所以我需要合并 Time 和 Id

标签: pythondataframeerror-handlingmerge

解决方案


您是否尝试过将“id”列转换为 str 或 int?

抱歉,我没有足够的声誉来评论您的问题。


推荐阅读