使用重采样对齐 pandas 中的多个时间序列 [英] Using resample to align multiple timeseries in pandas

查看:117
本文介绍了使用重采样对齐 pandas 中的多个时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是设置代码:

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的第3个值):

Here's what the data looks like in a table (3rd value for APOL isn't shown):

目标是将数据与日历四分之一标记对齐,以便可以比较3个数据集.只需看一下以下日期(2012年3月,2011年12月和2011年9月),就可以找到合理的组合标记.

The goal is to align the data to calendar quarter markers so the 3 data sets can be compared. Just glancing at the below dates, Mar 2012, Dec 2011, and Sep 2011 seem like reasonable markers for alignment.

以下是带有fill_method ='ffill'的输出:

Here's the output with 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

看起来像这样:

请注意每个系列中最新的数字是如何排列的.

Notice how the most recent numbers in each series don't line up.

这是带有fill_method ='bfill'的输出:

And here's the output with 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

看起来像这样:

同样,该系列中的最新数字也不符合要求.

Again, the most recent numbers in the series don't line up.

在这种情况下,这是resample()的预期输出吗?

Is this the expected output of resample() in this scenario?

我该怎么做才能得到上面三个最近的数字对齐并且其他所有字符都正确排列的结果?

What can I do to get results where the most recent 3 numbers above are aligned and everything else follows appropriately?

编辑:这是所需的输出:

推荐答案

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

这篇关于使用重采样对齐 pandas 中的多个时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆