简体   繁体   中英

Retrieve specific time intervals of pandas dataframe with datetime index

I have a pandas dataframe with a datetime index. Suppose the datetime index starts at time t1, is there a way in pandas to return the rows of the dataframe for every say 15-minute time interval starting from time t1?

Further, is it possible to average all the entries between those 15-minute intervals and return those?

Datetime            Value
2018-10-08 00:00:01 100.70
2018-10-08 00:00:20 98.70
2018-10-08 00:00:34 112.60
2018-10-08 00:00:00 38.30
2018-10-08 00:01:02 60.30
2018-10-08 00:01:24 115.85
2018-10-08 00:02:00 76.10

Currently, I solve this problem for 1-hour long intervals by making my own time_intervals and using between_time, but I feel like there should be a much niftier way to do this using the pandas datetime index.

time_intervals=[("{}:00:00".format(i),"{}:00:00".format(i+1)) for i in range(23)]


means_list=[df.between_time(time_interval[0],time_interval[1]).mean()[0] for time_interval in time_intervals]

"I have a pandas dataframe with a datetime index. Suppose the datetime index starts at time t1, is there a way in pandas to return the rows of the dataframe for every say 15-minute time interval starting from time t1?"

This is best to be solved by using resample : If you want to get the first element of a given time block, use

df.resample('15m').first()

if you however want to get the last element in a given time block, you should go with

df.resample('15m').last()

"Further, is it possible to average all the entries between those 15-minute intervals and return those?"

Yes, also this can be done with resample :

df.resample('15m').mean()

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