使用重采样对齐pandas中的多个时间序列

2024-05-28 20:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

设置代码如下:

import pandas
from datetime import datetime

a_values = [1728, 1635, 1733]
a_index = [datetime(2011, 10, 31), datetime(2012, 1, 31), datetime(2012, 4, 30)]
a = pandas.Series(data=a_values, index=a_index)

aa_values = [6419, 5989, 6006]
aa_index = [datetime(2011, 9, 30), datetime(2011, 12, 31), datetime(2012, 3, 31)]
aa = pandas.Series(data=aa_values, index=aa_index)

apol_values = [1100, 1179, 969]
apol_index = [datetime(2011, 8, 31), datetime(2011, 11, 30), datetime(2012, 2, 29)]
apol = pandas.Series(data=apol_values, index=apol_index)

表中的数据如下所示(APOL的第三个值未显示):

enter image description here

目标是将数据与日历季度标记对齐,以便可以比较3个数据集。仅仅看看下面的日期,2012年3月,2011年12月和2011年9月似乎是合理的标记。在

以下是fill\u method='ffill'的输出:

^{pr2}$

看起来像这样:

enter image description here

注意每个系列中最近的数字是如何不一致的。在

下面是fill_method='bfill'的输出:

In [9]: a.resample('Q', fill_method='bfill')
Out[9]: 
2011-12-31    1635
2012-03-31    1733
2012-06-30     NaN
Freq: Q-DEC

In [10]: aa.resample('Q', fill_method='bfill')
Out[10]: 
2011-09-30    6419
2011-12-31    5989
2012-03-31    6006
Freq: Q-DEC

In [11]: apol.resample('Q', fill_method='bfill')
Out[11]: 
2011-09-30    1179
2011-12-31     969
2012-03-31     NaN
Freq: Q-DEC

看起来像这样:

enter image description here

同样,这个系列中最近的数字并不一致。在

这是在这个场景中resample()的预期输出吗?在

我能做些什么来得到结果,上面最近的3个数字是一致的,其他的都是正确的?在

编辑:以下是所需的输出:

enter image description here


Tags: 数据inpandasdatadatetimeindex数字fill

热门问题