python - 使用重采样对齐 Pandas 中的多个时间序列

标签 python time-series pandas resampling

这是设置代码:

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_method='ffill' 的输出:

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

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

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

看起来像这样:

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

最佳答案

df1 = DataFrame({'a':a})
df2 = DataFrame({'aa':aa})
df3 = DataFrame({'apol':apol})
df=df1.append([df2,df3]).sort_index()
print df.resample('Q-APR',loffset='-1m').T

输出:

      2011-09-30  2011-12-31  2012-03-31
a           1728        1635        1733
aa          6419        5989        6006
apol        1100        1179         969

关于python - 使用重采样对齐 Pandas 中的多个时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13185454/

相关文章:

python - 使用 pandas python 计算每日气候学

python - 通过匹配列表中的字符串值在 Pandas 数据框中构建新列

Python - 如何在大文件中搜索字符串

python - 在流程开始执行后(在完成之前)向 subprocess.Popen() 提供标准输入

r - Python中时间序列的时间分解

python - 分割日期时间、python、pandas

python - 在 numpy 中获取索引子集的有效方法

Python:读取 CSV 到列表是否比 CSV 更快以使用键检查来听写?

python - 如何从 api 响应中提取 application/zip?

python - 如何使用字典存储 pandas 数据框