【问题标题】:Pandas resample time series in equal partsPandas 以相等的部分重新采样时间序列
【发布时间】:2015-04-21 11:21:45
【问题描述】:

我正在尝试以 N 个相等的部分重新采样 pandas 时间序列。

我的时间序列大小为 10

rng = pd.date_range('20130101',periods=10,freq='T')
ts=pd.Series(np.random.randn(len(rng)), index=rng)

print(ts)
2013-01-01 00:00:00   -1.346024
2013-01-01 00:01:00    0.671637
2013-01-01 00:02:00    0.435566
2013-01-01 00:03:00    1.043379
2013-01-01 00:04:00    0.877782
2013-01-01 00:05:00   -1.216598
2013-01-01 00:06:00    0.801525
2013-01-01 00:07:00    1.041827
2013-01-01 00:08:00   -0.309048
2013-01-01 00:09:00    0.212750
Freq: T, dtype: float64

如何在 N 等份中重新采样,N 大于 10

我希望答案当然有一些 NaN。

我希望看起来像 (N=12):

2013-01-01 00:00:00   -1.346024
2013-01-01 00:00:50    0.671637
2013-01-01 00:01:40    0.435566
2013-01-01 00:02:30    1.043379
2013-01-01 00:03:20    0.877782
2013-01-01 00:04:10         NaN
2013-01-01 00:05:00   -1.216598
2013-01-01 00:05:50    0.801525
2013-01-01 00:06:40    1.041827
2013-01-01 00:07:30   -0.309048
2013-01-01 00:08:20    0.212750
2013-01-01 00:09:10         NaN
Freq: 50S, dtype: float64

注意:以下代码适用于 N

length = 9
timeSpan = (ts.index[-1]-ts.index[0]+timedelta(minutes=1))
rule = int(timeSpan.total_seconds()/length)
tsNew=ts.resample(str(rule)+"S")

print(tsNew)
2013-01-01 00:00:00   -0.337194
2013-01-01 00:01:06    0.435566
2013-01-01 00:02:12    1.043379
2013-01-01 00:03:18    0.877782
2013-01-01 00:04:24   -1.216598
2013-01-01 00:05:30    0.801525
2013-01-01 00:06:36    1.041827
2013-01-01 00:07:42   -0.309048
2013-01-01 00:08:48    0.212750
Freq: 66S, dtype: float64

注意:如果可能的话,我希望答案仍然与多列时间序列兼容(例如 Open/High/Low/Close 金融系列)

【问题讨论】:

    标签: python pandas time-series finance resampling


    【解决方案1】:

    解决了。 resample 方法应该同时使用 fill_method='pad' 和 closed='right'

    tsNew=ts.resample(str(rule)+"S", fill_method='pad',closed='right')
    
    ts
    2013-01-01 00:00:00   -1.827784
    2013-01-01 00:01:00   -2.181001
    2013-01-01 00:02:00   -2.498234
    2013-01-01 00:03:00   -0.646579
    2013-01-01 00:04:00   -0.720016
    2013-01-01 00:05:00    1.298624
    2013-01-01 00:06:00   -0.785790
    2013-01-01 00:07:00    0.769829
    2013-01-01 00:08:00   -0.877086
    2013-01-01 00:09:00   -0.311500
    Freq: T, dtype: float64
    
    tsNew (for N=12)
    2013-01-01 00:00:00   -1.827784
    2013-01-01 00:00:50   -1.827784
    2013-01-01 00:01:40   -2.181001
    2013-01-01 00:02:30   -2.498234
    2013-01-01 00:03:20   -0.646579
    2013-01-01 00:04:10   -0.720016
    2013-01-01 00:05:00    1.298624
    2013-01-01 00:05:50    1.298624
    2013-01-01 00:06:40   -0.785790
    2013-01-01 00:07:30    0.769829
    2013-01-01 00:08:20   -0.877086
    2013-01-01 00:09:10   -0.311500
    Freq: 50S, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-24
      • 2019-01-18
      • 2015-11-07
      • 1970-01-01
      • 2018-03-14
      • 2016-10-03
      • 2013-01-09
      • 2018-03-18
      相关资源
      最近更新 更多