从某个索引值开始选择pandas数据帧中的行

时间:2017-03-17 23:28:42

标签: python pandas time-series

假设我有一个数据框,其中行由交易天索引,所以类似于:

{{1}}

我想找到以(比如)2017-2-28开头的$ N $行,所以我不知道日期范围,我只知道我要做十行的事情。这样做最优雅的方式是什么? (有很多丑陋的方式......)

2 个答案:

答案 0 :(得分:3)

我的快速回答

s = df.Date.searchsorted(pd.to_datetime('2017-2-28'))[0]
df.iloc[s:s + 10]

演示

df = pd.DataFrame(dict(
        Date=pd.date_range('2017-01-31', periods=90, freq='B'),
        ClosingPrice=np.random.rand(90)
    )).iloc[:, ::-1]

date = pd.to_datetime('2017-3-11')
s = df.Date.searchsorted(date)[0]
df.iloc[s:s + 10]

         Date  ClosingPrice
29 2017-03-13      0.737527
30 2017-03-14      0.411525
31 2017-03-15      0.794309
32 2017-03-16      0.578911
33 2017-03-17      0.747763
34 2017-03-20      0.081113
35 2017-03-21      0.000058
36 2017-03-22      0.274022
37 2017-03-23      0.367831
38 2017-03-24      0.100930

天真时间测试

enter image description here

答案 1 :(得分:2)

df[df['Date'] >= Date(2017,02,28)][:10] 

我想?