【发布时间】:2017-05-23 15:11:42
【问题描述】:
我有 2 个数据框,它们看起来与下面的一个非常接近(有额外的列,但不应该影响结果):
编辑:根据要求添加了额外的变量。 - 号表示缺失数据
数据框1
ProductID Date Booked Rate
10 01/01/2017 10.0
10 02/01/2017 0.3
10 03/01/2017 70.4
20 01/01/2017 100.0
20 02/01/2017 70.0
20 03/01/2017 0.1
- 04/01/2017 0.5
dataframe2
ProductID Date Actual Rate
10 01/01/2017 11.0
10 02/01/2017 12.3
10 03/01/2017 75.4
20 01/01/2017 110.0
20 02/01/2017 80.0
30 03/01/2017 10.1
- 04/01/2017 0.7
理想情况下,结果应该是 dataframe 3:
ProductID Date Booked Rate Actual Rate
10 01/01/2017 10.0 11.0
10 02/01/2017 0.3 12.3
10 03/01/2017 70.4 75.4
20 01/01/2017 100.0 110.0
20 02/01/2017 70.0 80.0
20 03/01/2017 0.1 -
- 04/01/2017 0.5 -
当我对我的真实数据集进行合并时,使用以下代码:
df3 = pd.merge(left=df1, right=df2, how="left", left_on=["ProductID", "Date"], right_on=["ProductID", "Date"])
我得到了错误的结果,因为额外列中的数字(为清楚起见而省略)有时会加倍/三倍。
编辑: 这似乎是因为它将 dataframe1 中的空 ProductID 字段与 dataframe2 中的空 productID 匹配。我需要省略这个。
我真正需要的是一个简单的合并,当它在 dataframe1 中找到与 productId 和 Date 匹配时,将 dataframe2 的实际速率添加为新列。应排除 dataframe2 中的任何额外项,并且不应排除 dataframe1 中的任何匹配项。
我也试过了,对,内,外,合并。
它似乎总是以完全相同的方式扭曲结果(将某些订单项加倍和三倍)。
【问题讨论】:
-
格式错误的日期是故意的吗?
-
-是否意味着它缺少或等于字符串'-'?
标签: pandas join dataframe merge