在时间序列中上采样并插值数据

时间:2018-08-12 08:41:09

标签: pandas interpolation resampling

我需要在一个时间序列中执行一次上采样,然后对数据进行插值,我想找到最佳的方法。时间序列的间隔不是固定的。我展示了一个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

1 个答案:

答案 0 :(得分:2)

您可以进行多个索引,将日期时间转换为数字-本地numpy数组(以纳秒为单位),因此可以通过reindexinterpolate添加新的NaN行。最后将time列转换回datetime

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
相关问题