简体   繁体   中英

Pandas: Selecting rows by time

I have a dataframe with the following structure:

Date       | Hour     | Duration 
2014-05-12 | 20:05:20 | 2.20
2014-05-12 | 20:06:20 | 4.20
2014-05-12 | 22:05:22 | 3.10
2014-05-12 | 08:05:20 | 7.10

How can I create another dataframe that contains only rows where the values in the time column are between 20:00:00 and 6:59:59?

We can using between

m=pd.to_timedelta(df.Hour).between('06:59:59','20:00:00')
df1=df[~m].copy()

There's between_time if you're willing to make a DatetimeIndex . Not too different from between , but it deals with the 24 hour clock appropriately.

df.index = pd.to_datetime(df.Date + ' ' + df.Hour)
df.between_time('20:00:00', '6:59:59')

#                           Date      Hour  Duration
#2014-05-12 20:05:20  2014-05-12  20:05:20       2.2
#2014-05-12 20:06:20  2014-05-12  20:06:20       4.2
#2014-05-12 22:05:22  2014-05-12  22:05:22       3.1

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