Python Pandas: How to drop rows by time?

Viewed 80

I want to keep rows with time that are between 6am (morning) and 12am (midnight), how should I do it?

This is my dataframe: enter image description here

and this is the datatype: enter image description here

I tried this but doesn't work:

daytime_start = '06:00:00'
daytime_end = '23:59:59'
mask = (df['Time'] >= daytime_start) & (df['Time'] <= daytime_end)
filtered_df = df.loc[mask]
2 Answers

Use df.between_time:

df.set_index('Date Time').between_time('6:00', '23:59').reset_index()

using query

df.query('index < @start_remove or index > @end_remove')

using loc

df.loc[(df.index < start_remove) | (df.index > end_remove)]

using date slicing

This includes the end points

pd.concat([df[:start_remove], df[end_remove:]]) 
Related