selecting rows in a pandas dataframe starting with a certain index value

270
March 18, 2017, at 10:48 AM

Suppose I have a dataframe, where the rows are indexed by trading days, so something like:

Date          ClosingPrice
2017-3-16      10.00
2017-3-17      10.13
2017-3-20      10.19
    ...

I want to find $N$ rows starting with (say) 2017-2-28, so I don't know the date range, I just know that I want to do something ten rows down. What is the most elegant way of doing this? (there are plenty of ugly ways...)

Answer 1

my quick answer

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

demo

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

naive time test

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

I guess?

READ ALSO
get values from input data

get values from input data

I have input dataset in keyvalue with delimiter as below,

351
type() input, print based on data type()

type() input, print based on data type()

Write a function data_type which takes an argument and prints out the data type of that argumentSo if we give a string as input it will say that our input is a string and same if we give an integer or a float

261
How to fetch all databases, tables, schema over multiple MySQL instances

How to fetch all databases, tables, schema over multiple MySQL instances

The task infront of me is to basically inventory all of our databases, their tables, and the tables' schema over each MySQL instance we have internally (about 20)

311