简体   繁体   中英

Slice efficiently pandas datetime index by a specific time

What is the most efficient way to get all the rows of a dataframe with a specific time? For instance, if I create the following DataFrame,

df = DataFrame(index=pd.date_range('2010-01-01', '2016-04-01',freq='min'))

and then try to get all the rows with a 3pm time:

%timeit df[df.index.time == time(15,0)]
1 loops, best of 3: 9.29 s per loop

it works but it is very slow.

Also, what about efficiently slicing between two specific times ?

%timeit df[(df.index.time >= time(15,0)) & (df.index.time <= time(16,0))]
1 loops, best of 3: 18.7 s per loop

You can use at_time and between_time :

print df.at_time('15:00')

print df.between_time(start_time='15:00', end_time='16:00')

尝试这个:

df.loc[df.index.hour == 15]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM