Search code examples
pythonpandasdatetimedataframeperiod

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


Pandas has a fast query method that works very well but I could not use it to work with period indexes? It works with datetime index but not with Period index!


Solution

  • Demo:

    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