datetime或period类型的索引如何使用Pandas.DataFrame查询方式?

How to use Pandas.DataFrame query method for index of datetime or period type?

Pandas 有一个非常有效的快速查询方法,但我不能用它来处理期间索引? 它适用于日期时间索引,但不适用于期间索引!

演示:

In [42]: df = pd.DataFrame({'val':np.random.rand(13)}, 
                           pd.period_range('1/1/2011', '1/1/2012', freq='M'))

In [43]: df
Out[43]:
              val
2011-01  0.243320
2011-02  0.123101
2011-03  0.240437
2011-04  0.883524
2011-05  0.428512
2011-06  0.949718
2011-07  0.240610
2011-08  0.436306
2011-09  0.290508
2011-10  0.800408
2011-11  0.594732
2011-12  0.401684
2012-01  0.590237

In [44]: p1 = pd.Period('2011-03', freq='M')

In [45]: p2 = pd.Period('2011-08', freq='M')

In [46]: df.query("@p1 < index < @p2")
Out[46]:
              val
2011-04  0.883524
2011-05  0.428512
2011-06  0.949718
2011-07  0.240610