问题描述
我正在尝试向df2添加新列,以标识两个数据框日期列中的日期之间的匹配项。如果日期匹配(时间对于匹配不重要),则在“匹配”列中打印“ 1”。以下是两个数据框和所需的输出,我不知道该如何实现。
df1:
date
0 2019-05-03 12:22:03
1 2019-05-06 13:56:00
2 2019-05-08 11:25:53
3 2019-05-09 06:11:14
4 2019-05-13 23:36:18
df2:
date Location
0 2019-05-09 12:00:00 Area_A
1 2019-05-10 14:00:00 Area_B
2 2019-05-11 13:00:00 Area_C
3 2019-05-12 11:00:00 Area_D
4 2019-05-13 12:00:00 Area_A
5 2019-05-14 14:00:00 Area_C
6 2019-05-15 12:00:00 Area_B
7 2019-05-16 12:00:00 Area_A
8 2019-05-17 13:00:00 Area_A
9 2019-05-18 18:00:00 Area_B
Desired output df2:
date Location Match
0 2019-05-09 12:00:00 Area_A 1
1 2019-05-10 14:00:00 Area_B
2 2019-05-11 13:00:00 Area_C
3 2019-05-12 11:00:00 Area_D
4 2019-05-13 12:00:00 Area_A 1
5 2019-05-14 14:00:00 Area_C
6 2019-05-15 12:00:00 Area_B
7 2019-05-16 12:00:00 Area_A
8 2019-05-17 13:00:00 Area_A
9 2019-05-18 18:00:00 Area_B
解决方法
在两个df中都创建另一列“ _date”,其中只有日期,没有时间部分。
df1["_dates"] = column with only dates (may be df1['dates'].dt.date)
df2["_dates"] = column with only dates (may be df2['dates'].dt.date)
df1["Match"] = 1
现在在“ _dates”合并这两个数据框
pd.merge(df1,df2,left_on='_dates',right_on='_dates',how='right')