python - 将两个时间序列与 tz 感知的日期时间索引相结合
问题描述
我time-series
下面有两个。df1
有一个 DateTime 格式的索引,包括date
和hour
不包括分钟和秒。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.
解决方案
您可以在df2merge
之后set_index
的两个数据帧,例如:floor
index
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
推荐阅读
- r - 如何从r中的字符串中删除ascii字符
- android - 如何使用android TimePicker每小时强制它
- vb.net - 选择案例和错误连接多个表
- android - 如何使用 FragmentManager 更新片段?
- javascript - 为了使用聚类,我是否需要向我的地图添加源?
- java - @Valid (javax.validation.Valid) 对于列表类型不是递归的
- dart - 如何捕获泛型约束的泛型类型?
- java - 当通过 Spark 反序列化/序列化时,使用 void 方法进行模拟会导致“本地类名与流类名“void”不兼容”
- javascript - Zdog Box 高度不会增长
- angular - Angular Interceptor modify headers change request method