Get TypeError: Index must be DatetimeIndex when filtering dataframe

Viewed 11491

I want to filter the dataframe by a certain datatime period like the following code.

df2 = df2['Dates'].between_time(pandas.to_datetime('5/13/2015 8:41'), pandas.to_datetime('5/13/2015 8:55'))[['Dates','Category']]

but got an error 'TypeError: Index must be DatetimeIndex' This is the dataframe

enter image description here

and I tried

df2 = pandas.read_csv(path2,parse_dates=[0])

like one of the response from other post but still got the same error. Does anyone know what happen here?

2 Answers

If you want to filter df by a certain datetime period, you can try with:

start_date = pandas.to_datetime('5/13/2015 8:41')
end_date = pandas.to_datetime('5/13/2015 8:55')
df2.loc[(df2['Dates'] > start_date) & (df2['Dates'] < end_date)]

As what you offer I think the index's is not the DatetimeIndex so you may try :

df2.index=pd.to_datetime(df2.index)
Related