pandas 基于日期索引的数据帧切片行

pandas dataframe slice rows based on date indexes

我已经阅读了csv文件中的历史行情数据,如下

df = pandas.read_csv('http://real-chart.finance.yahoo.com/table.csv?s=AAPl', 
            index_col=0, parse_dates=True)
df.head()   


              Open       High        Low      Close     Volume    Adj Close
Date                                                                       
2016-02-12  94.190002  94.500000  93.010002  93.989998  40121700  93.989998
2016-02-11  93.790001  94.720001  92.589996  93.699997  49686200  93.699997
2016-02-10  95.919998  96.349998  94.099998  94.269997  42245000  94.269997
2016-02-09  94.290001  95.940002  93.930000  94.989998  44331200  94.989998
2016-02-08  93.129997  95.699997  93.040001  95.010002  54021400  95.010002

所以,我使用给定的日期作为行索引,我想对这个数据框进行切片,例如 select 2008-01-01 到 2015-12-31 之间的所有行

我试过这个命令

df.loc['20080101':'200151231']

但它 return 没有任何输出。

您的索引似乎是反向排序的。您可以通过 df.sort_index(inplace=True) 再次对其进行排序,或者执行以下操作来反转索引,然后使用索引选择:

>>> df[::-1].ix['2016-02-09':'2016-02-11']
                 Open       High        Low      Close    Volume  Adj_Close
Date                                                                       
2016-02-09  94.290001  95.940002  93.930000  94.989998  44331200  94.989998
2016-02-10  95.919998  96.349998  94.099998  94.269997  42245000  94.269997
2016-02-11  93.790001  94.720001  92.589996  93.699997  49686200  93.699997