首页 > 解决方案 > 将两个时间序列与 tz 感知的日期时间索引相结合

问题描述

time-series下面有两个。df1有一个 DateTime 格式的索引,包括datehour不包括分钟和秒。df2具有完整的日期时间索引,也是日期时间格式。在完整的数据中,df1 在行数上比 df2 短很多。Datetime两者的索引df是时区(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.

标签: pythonpandasdatetimetimezone

解决方案


您可以在df2merge之后set_index的两个数据帧,例如:floorindex

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

推荐阅读