我在下面有两个time-series
。df1
有一个日期时间格式的索引,其中包括date
和hour
,没有分钟和秒。df2
具有完整的日期时间索引,也采用日期时间格式。在完整数据中,df1 在行数方面比 df2 短得多。 两个df
的Datetime
索引是时区 (tz( 感知的。
如您所见,两个数据集的时间范围从凌晨 4 点到上午 8 点。 然而,df1
会跳过一些小时,而在df2
,所有时间都可用。注意:在此示例中,仅跳过奇数小时,但在完整数据中并非如此。
DF1
value1
date
2016-04-01 04:00:00+07:00 16
2016-04-01 06:00:00+07:00 76
2016-04-01 08:00:00+07:00 23
DF2
value2
DateTime
2016-04-01 04:00:00+07:00 257.96
2016-04-01 04:15:00+07:00 317.58
2016-04-01 04:30:00+07:00 333.39
2016-04-01 04:45:00+07:00 333.39
2016-04-01 05:00:00+07:00 449.96
2016-04-01 05:15:00+07:00 466.42
2016-04-01 05:30:00+07:00 498.56
2016-04-01 05:45:00+07:00 454.73
2016-04-01 06:00:00+07:00 472.45
2016-04-01 06:15:00+07:00 489.85
2016-04-01 06:30:00+07:00 169.54
2016-04-01 06:45:00+07:00 276.13
2016-04-01 07:00:00+07:00 293.70
2016-04-01 07:15:00+07:00 108.05
2016-04-01 07:30:00+07:00 179.21
2016-04-01 07:45:00+07:00 201.80
2016-04-01 08:00:00+07:00 201.80
2016-04-01 08:15:00+07:00 201.80
2016-04-01 08:30:00+07:00 201.80
2016-04-01 08:45:00+07:00 201.80
我想按索引合并两个数据集。 df1 应控制要保留的小时。预期结果如下。
value2 value1
DateTime
2016-04-01 04:00:00+07:00 257.96 16
2016-04-01 04:15:00+07:00 317.58 16
2016-04-01 04:30:00+07:00 333.39 16
2016-04-01 04:45:00+07:00 333.39 16
2016-04-01 06:00:00+07:00 472.45 76
2016-04-01 06:15:00+07:00 489.85 76
2016-04-01 06:30:00+07:00 169.54 76
2016-04-01 06:45:00+07:00 276.13 76
2016-04-01 08:00:00+07:00 201.80 23
2016-04-01 08:15:00+07:00 201.80 23
2016-04-01 08:30:00+07:00 201.80 23
2016-04-01 08:45:00+07:00 201.80 23
这是我的尝试。
result = pd.concat([df2, df1], sort=True)
# returns no error. only combine the two df horizontally. df1 does not control the DateTime index in the result.
result = df2.merge(df1, left_index=True, right_index=True)
# returns error.
您可以在set_index
df2index
的floor
后merge
这两个数据帧,如下所示:
print (df1.merge( df2.reset_index().set_index(df2.index.floor('H')),
how='left', left_index=True, right_index=True).set_index('DateTime'))
value1 value2
DateTime
2016-04-01 04:00:00+07:00 16 257.96
2016-04-01 04:15:00+07:00 16 317.58
2016-04-01 04:30:00+07:00 16 333.39
2016-04-01 04:45:00+07:00 16 333.39
2016-04-01 06:00:00+07:00 76 472.45
2016-04-01 06:15:00+07:00 76 489.85
2016-04-01 06:30:00+07:00 76 169.54
2016-04-01 06:45:00+07:00 76 276.13
2016-04-01 08:00:00+07:00 23 201.80
2016-04-01 08:15:00+07:00 23 201.80
2016-04-01 08:30:00+07:00 23 201.80
2016-04-01 08:45:00+07:00 23 201.80