在python中合并具有不同时间频率的系列/数据帧

2023-12-02

我正在尝试合并两个系列,一个以小时为单位,另一个以分钟为单位(并将索引保​​持在分钟级别):

Series A:

time
2017-09-01 01:00:00   0.5
2017-09-01 02:00:00   0.4
Freq: H, Name: A, dtype: float64

B 系列分钟:

Series B

time
2017-09-01 00:00:00         NaN
2017-09-01 00:03:00   -0.000350
2017-09-01 00:06:00    0.000401
Name: B, dtype: float64

我想按小时合并两个系列。所需的合并数据框将是:

time
2017-09-01 00:00:00         NaN       0.5
2017-09-01 00:03:00   -0.000350       0.5
2017-09-01 00:06:00    0.000401       0.5
2017-09-01 01:00:00    0.002301       0.4
2017-09-01 01:03:00    0.005601       0.4

在搜索SO后,我发现的一种方法是在B系列中创建一个“小时”列,然后使用A的索引和B的“小时”列将A连接到B:(参考:在 Pandas 中合并/组合两个具有不同频率时间序列索引的数据帧?)

B = B.to_frame()
B['hour'] = B.index.to_period('H')
merged = B.join(A, on = 'hour', how = 'left')

但我收到错误消息:

TypeError: Argument 'values' has incorrect type (expected numpy.ndarray, got Index)

有谁知道如何解决这个问题?或者也许有更好的方式将这两个系列结合起来?多谢!


Demo:

In [280]: A
Out[280]:
time
2017-09-01 01:00:00    0.5
2017-09-01 02:00:00    0.4
Name: val, dtype: float64

In [281]: B
Out[281]:
time
2017-09-01 00:00:00         NaN
2017-09-01 00:03:00   -0.000350
2017-09-01 00:06:00    0.000401
Name: val, dtype: float64

In [282]: B.to_frame('B').join(A.to_frame('A').set_index(A.index.shift(-1, freq='H')).resample('3T').ffill())
Out[282]:
                            B    A
time
2017-09-01 00:00:00       NaN  0.5
2017-09-01 00:03:00 -0.000350  0.5
2017-09-01 00:06:00  0.000401  0.5
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在python中合并具有不同时间频率的系列/数据帧 的相关文章

随机推荐