gpt4 book ai didi

python - 将两个时间序列与 tz 感知的日期时间索引结合起来

转载 作者:行者123 更新时间:2023-12-01 06:34:51 25 4
gpt4 key购买 nike

我下面有两个时间序列df1 有一个 DateTime 格式的索引,其中包括日期小时,不包括分和秒。 df2 具有完整的日期时间索引,也是日期时间格式。全量数据中,df1的行数比df2短很多。两个 dfDatetime 索引可识别时区 (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 之后合并两个数据帧floor df2 的索引,例如:

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

关于python - 将两个时间序列与 tz 感知的日期时间索引结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59723507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com