Skip to main content
 首页 » 编程设计

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

2025年01月19日10Leo_wl

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

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:(引用:Merging/combining two dataframes with different frequency time series indexes in 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) 

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

请您参考如下方法:

演示:

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