我需要在时间序列中执行上采样,然后插入数据,我想找到最好的方法来做到这一点。时间序列没有恒定的间隔。我展示了一个数据帧示例和我正在寻找的结果。在结果示例中,我仅插入 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
最佳答案
您可以使用多个索引,将日期时间转换为数字 - 以纳秒为单位的 native numpy 数组,因此可以通过 reindex
添加新的 NaN
行和 interpolate
。最后将 time
列转换回 datetime
s:
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
关于pandas - 在时间序列中上采样并插值数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51807167/