Pandas时间序列比较

5

我希望获得两个时间序列重叠部分的平均差异。然而,它们的范围和间隔都不同。如何解决这两个问题?

示例数据:

Series 1:
2014-08-05 05:03:00    25.194      
2014-08-05 05:08:00    25.196      
2014-08-05 05:13:00    25.197      
2014-08-05 05:18:00    25.199      
2014-08-05 05:23:00    25.192      

Series 2:
2014-08-05 05:12:00    25.000000
2014-08-05 05:13:00    25.000000
2014-08-05 05:14:00    25.000000

你能提供一些示例数据来说明问题吗? - joris
这个例子的期望输出是什么? - joris
系列之间的平均差异。 - mikael
那是什么?索引不同,所以差异在哪里?它们应该如何对齐?最好您展示一下期望的输出。 - joris
如何使用插值方法将一个序列重新采样为另一个序列的索引? - mikael
什么样的插值?向前填充,基于时间索引的线性插值,还是其他的?(参见http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html和http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.interpolate.html)。再次强调,如果您展示所需的输出,将更容易理解。 - joris
1个回答

11

这符合您的要求吗?

首先,您可以使用align对两个序列进行对齐(使它们具有相同的索引)。还可以使用reindex将其中一个序列重新索引为另一个序列的索引:

In [85]: s1, s2 = s1.align(s2)

In [86]: s1
Out[86]: 
2014-08-05 05:03:00    25.194
2014-08-05 05:08:00    25.196
2014-08-05 05:12:00       NaN
2014-08-05 05:13:00    25.197
2014-08-05 05:14:00       NaN
2014-08-05 05:18:00    25.199
2014-08-05 05:23:00    25.192
dtype: float64

In [87]: s2
Out[87]: 
2014-08-05 05:03:00   NaN
2014-08-05 05:08:00   NaN
2014-08-05 05:12:00    25
2014-08-05 05:13:00    25
2014-08-05 05:14:00    25
2014-08-05 05:18:00   NaN
2014-08-05 05:23:00   NaN
dtype: float64

然后您可以插值缺失的值(例如,基于时间索引使用线性插值):

In [88]: s1.interpolate(method='time')
Out[88]: 
2014-08-05 05:03:00    25.1940
2014-08-05 05:08:00    25.1960
2014-08-05 05:12:00    25.1968
2014-08-05 05:13:00    25.1970
2014-08-05 05:14:00    25.1974
2014-08-05 05:18:00    25.1990
2014-08-05 05:23:00    25.1920
dtype: float64

然后只需将两个系列相减即可得到差异:

In [91]: s = s1.interpolate(method='time') - s2.interpolate(method='time')

In [92]: s
Out[92]: 
2014-08-05 05:03:00       NaN
2014-08-05 05:08:00       NaN
2014-08-05 05:12:00    0.1968
2014-08-05 05:13:00    0.1970
2014-08-05 05:14:00    0.1974
2014-08-05 05:18:00    0.1990
2014-08-05 05:23:00    0.1920
dtype: float64

In [93]: s.mean()
Out[93]: 0.19643999999999906

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接