BML91
BML91

Reputation: 3180

How to index pandas DataFrames by selecting times in a particular interval?

I have a DataFrame in a similar layout to the following:

In [24]: example_df
Out[24]:
                      Price
DateTime
2012-09-11 19:44:00   99.622
2012-09-11 19:45:00   99.312
2012-09-11 19:46:00   99.211
2012-09-11 19:47:00   99.757
2012-09-11 19:48:00   99.312
2012-09-11 19:49:00   99.157
2012-09-11 19:50:00   99.751
...

The DataFrame has a datetime index.

This DataFrame spans many years minute by minute, how would I go about slicing the data to only contain a certain time period from every day in the time series? Say 12:00-13:00 for every single day in the DataFrame?

Upvotes: 3

Views: 463

Answers (1)

Alex Riley
Alex Riley

Reputation: 176820

You could use indexer_between_time() to capture the indices lying in a given time intervals and then iloc to slice the DataFrame. For example:

>>> df.iloc[df.index.indexer_between_time('19:45:00', '19:49:00')]
                      Price
2012-09-11 19:45:00  99.312
2012-09-11 19:46:00  99.211
2012-09-11 19:47:00  99.757
2012-09-11 19:48:00  99.312
2012-09-11 19:49:00  99.157

For your specific request of entries between 12:00 to 13:00 for every single day, you can fetch the rows with:

df.iloc[df.index.indexer_between_time('12:00:00', '13:00:00')]

Upvotes: 4

Related Questions