时间序列中的上采样和插值数据

upsample in a timeseries and interpolating data

我需要在时间序列中执行上采样,然后对数据进行插值,我想找到执行此操作的最佳方法。时间序列没有恒定的间隔。我展示了一个 DatFrame 示例和我正在查看的结果。在结果示例中,我仅插入 1 行。如果能够插入 n 行就太好了。

data = {'time': ['08-12-2018 10:00:00','08-12-2018 10:01:00','08-12-2018 \
10:01:30','08-12-2018 10:03:00','08-12-2018 10:03:10'], 'value':[1,2,3,4,5]}
df=pd.DataFrame(data)
df.time=pd.to_datetime(df.time)
df
Out[42]: 
                 time  value
0 2018-08-12 10:00:00      1
1 2018-08-12 10:01:00      2
2 2018-08-12 10:01:30      3
3 2018-08-12 10:03:00      4
4 2018-08-12 10:03:10      5

结果

                 time  value
0 2018-08-12 10:00:00      1
1 2018-08-12 10:00:30      1.5
2 2018-08-12 10:01:00      2
3 2018-08-12 10:01:15      2.5
4 2018-08-12 10:01:30      3
5 2018-08-12 10:02:15      3.5
6 2018-08-12 10:03:00      4
7 2018-08-12 10:03:05      4.5
8 2018-08-12 10:03:10      5

您可以创建多个索引,将日期时间转换为数字 - 以纳秒为单位的原生 numpy 数组,因此可以通过 reindex and interpolate 添加新的 NaNs 行。最后将 time 列转换回 datetimes:

N = 2
df.index = df.index * N
df.time= df.time.astype(np.int64)
df1 = df.reindex(np.arange(df.index.max() + 1)).interpolate()
df1.time=pd.to_datetime(df1.time)
print (df1)
                 time  value
0 2018-08-12 10:00:00    1.0
1 2018-08-12 10:00:30    1.5
2 2018-08-12 10:01:00    2.0
3 2018-08-12 10:01:15    2.5
4 2018-08-12 10:01:30    3.0
5 2018-08-12 10:02:15    3.5
6 2018-08-12 10:03:00    4.0
7 2018-08-12 10:03:05    4.5
8 2018-08-12 10:03:10    5.0