插入(上采样)非等间隔时间序列与Pandas版本18.0rc1等间隔

时间:2016-03-07 12:18:21

标签: python pandas

我想插入(upscale)nonequispaced时间序列以获得等间隔的时间序列。

目前我是按照以下方式进行的:

  1. 采取原始时间序列。
  2. 每隔30秒创建一个NaN值的新时间序列(使用重新采样(' 30S')。asfreq())
  3. concat原始时间序列和新时间序列
  4. 对时间序列进行排序以恢复次数(这我不喜欢 - 排序具有O = n log(n)的复杂性)
  5. 插值
  6. 从时间序列中删除原始点
  7. Pandas版本18.0rc1有更简单的方法吗?就像在matlab中一样,你有原始的时间序列,你将新的时间作为参数传递给interpolate()函数,以便在所需的时间接收值。

    我注意到原始时间序列的时间可能不是所需时间序列的时间子集。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    values = [271238, 329285, 50, 260260, 263711]
    timestamps = pd.to_datetime(['2015-01-04 08:29:4',
                                 '2015-01-04 08:37:05',
                                 '2015-01-04 08:41:07',
                                 '2015-01-04 08:43:05',
                                 '2015-01-04 08:49:05'])
    
    ts = pd.Series(values, index=timestamps)
    ts
    ts[ts==-1] = np.nan
    newFreq=ts.resample('60S').asfreq()
    
    new=pd.concat([ts,newFreq]).sort_index()
    new=new.interpolate(method='time')
    
    ts.plot(marker='o')
    new.plot(marker='+',markersize=15)
    
    new[newFreq.index].plot(marker='.')
    
    lines, labels = plt.gca().get_legend_handles_labels()
    labels = ['original values (nonequispaced)', 'original + interpolated at new frequency (nonequispaced)', 'interpolated values without original values (equispaced!)']
    plt.legend(lines, labels, loc='best')
    plt.show()
    

    image

1 个答案:

答案 0 :(得分:1)

有几种要求以更简单的方式插入所需值的方法(稍后我将在链接中进行编辑,但会在问题跟踪器中搜索插值问题)。所以将来会有一种更简单的方法。

现在你可以更清晰地编写选项

In [9]: (ts.reindex(ts.index | newFreq.index)
           .interpolate(method='time')
           .loc[newFreq.index])
Out[9]:
2015-01-04 08:29:00              NaN
2015-01-04 08:30:00    277996.070686
2015-01-04 08:31:00    285236.860707
2015-01-04 08:32:00    292477.650728
2015-01-04 08:33:00    299718.440748
                           ...
2015-01-04 08:45:00    261362.402778
2015-01-04 08:46:00    261937.569444
2015-01-04 08:47:00    262512.736111
2015-01-04 08:48:00    263087.902778
2015-01-04 08:49:00    263663.069444
Freq: 60S, dtype: float64

这仍然涉及您在上面列出的所有步骤,但索引的并集比结束和删除更简洁。