【问题标题】:Strange behavior of pandas resampling熊猫重采样的奇怪行为
【发布时间】:2013-08-18 21:14:47
【问题描述】:

我遇到了熊猫时间序列 (Python) 的重采样函数的一种相当奇怪的行为。我用的是最新版的熊猫(0.12.0)

采取以下时间序列:

dates = [datetime(2011, 1, 2, 1), datetime(2011, 1, 2, 2), datetime(2011, 1, 2, 3),
          datetime(2011, 1, 2, 4), datetime(2011, 1, 2, 5), datetime(2011, 1, 2, 6)]
ts = Series(np.arange(6.), index=dates)

然后尝试重新采样到 66s 和 65s。这是我得到的结果:

In [45]: ts.resample('66min')
Out[45]:
2011-01-02 01:00:00    0.5
2011-01-02 02:06:00    2.0
2011-01-02 03:12:00    3.0
2011-01-02 04:18:00    4.0
2011-01-02 05:24:00    5.0
Freq: 66T, dtype: float64

In [46]: ts.resample('65min')
Out[46]:
2011-01-02 01:00:00     0
2011-01-02 02:05:00   NaN
2011-01-02 03:10:00   NaN
2011-01-02 04:15:00   NaN
2011-01-02 05:20:00   NaN
2011-01-02 06:25:00   NaN
Freq: 65T, dtype: float64

我理解重采样到 66 秒时的行为。它总是取相应区间内所有值的平均值(默认值)。 我不明白也不知道如何影响 65 岁的行为。

这是一个简化的问题。背景是一个更复杂的数据校正过程,涉及重采样。

有什么想法吗?

【问题讨论】:

  • 您必须选择fill_method。您希望得到什么结果?

标签: python pandas time-series resampling


【解决方案1】:

也许您想要插值而不是重新采样。这是一种方法:

In [53]: index = pd.date_range(freq='66T', start=ts.first_valid_index(), periods=5)

In [54]: ts.reindex(set(ts.index).union(index)).sort_index().interpolate('time').ix[index]
Out[54]: 
2011-01-02 01:00:00    0.0
2011-01-02 02:06:00    1.1
2011-01-02 03:12:00    2.2
2011-01-02 04:18:00    3.3
2011-01-02 05:24:00    4.4
Freq: 66T, dtype: float64

In [55]: index = pd.date_range(freq='65T', start=ts.first_valid_index(), periods=5)

In [56]: ts.reindex(set(ts.index).union(index)).sort_index().interpolate('time').ix[index]
Out[56]: 
2011-01-02 01:00:00    0.000000
2011-01-02 02:05:00    1.083333
2011-01-02 03:10:00    2.166667
2011-01-02 04:15:00    3.250000
2011-01-02 05:20:00    4.333333
Freq: 65T, dtype: float64

也就是说,重新采样似乎可以改进。乍一看,你表现出的行为是神秘的,我同意,没有帮助。值得讨论。

【讨论】:

  • 这是一个非常好的方法,谢谢!看起来我的功能很有希望。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2013-06-04
  • 2015-11-21
相关资源
最近更新 更多