Select 行先于 as.freq() 出现

Select row prior as.freq() occurrence

我的目标是 select 使用时间序列分析 "as.freq" 定义的事件之前的一行,例如 'Q'(季度)、'EOM'、等...

例如,在下面的示例中,df.asfreq('Q') 产生以下结果:

import pandas as pd
import numpy as np 

dates = pd.date_range('20120101','20140101')
df =pd.DataFrame(np.random.randn(len(dates),1),index=dates,columns=list('A')) 

df.asfreq('Q')

df
            A
2012-03-31  0.207220
2012-06-30  1.154098
2012-09-30  0.928301
2012-12-31  0.457587
2013-03-31  1.063016
2013-06-30  -0.650549
2013-09-30  0.562216
2013-12-31  -1.978959

想要 select 行 "prior" 到第一季度末(以及随后的 'Q')出现(2012-03-31)以上:

2012-03-30  0.314567

或者,行表示从 2012-03-30 到 2012-03-27,三行 "prior" 到上面第一个季度末 (2012-03-31)。

pandas 的新手,尝试了几种方法,但暂时被难住了。

编辑:

尝试过:

df.loc[df.index == df.asfreq('Q')][-3]

TypeError: <class 'pandas.core.frame.DataFrame'> type object 

基本语法是这样的:

dataframe.loc[dataframe.index < 'date time value'][-n:]

其中 n 是后续或前面的行数。

例如:

In [49]: df.loc[df.index < '2012-03-31 00:00:00'][-3:]
Out[49]: 
                   A
2012-03-28 -0.252526
2012-03-29 -0.708683
2012-03-30 -0.056674

你可以用更多的运算符做更复杂的事情:

In [11]: df.loc[(df.index > '2012-03-31 00:00:00') & (df.index < '2012-06-30 00:00:00')].head()
Out[11]: 
                   A
2012-04-01 -0.172987
2012-04-02 -0.676806
2012-04-03 -1.320243
2012-04-04 -0.222272
2012-04-05  0.700445

请注意,当您使用 DatetimeIndex class.

时,这实际上仅适用于此特定情况

示例使用 df.asfreq('Q'):

In [16]: df.loc[(df.index < df.asfreq('Q').index[0])][-3:]
Out[16]: 
                   A
2012-03-28 -1.387065
2012-03-29  1.203649
2012-03-30 -0.668392