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

时间:2016-02-17 05:20:25

标签: python date pandas slice

我已经阅读了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

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

我试过这个命令

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

但它不会返回任何内容作为输出。

1 个答案:

答案 0 :(得分:2)

您的索引似乎是反向排序的。您可以通过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