Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get TypeError: Index must be DatetimeIndex when filtering dataframe

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?

like image 533
Eddie.Wu Avatar asked Oct 05 '17 02:10

Eddie.Wu


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)]
like image 144
Tiny.D Avatar answered Oct 31 '22 09:10

Tiny.D


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

df2.index=pd.to_datetime(df2.index)
like image 2
ileadall42 Avatar answered Oct 31 '22 07:10

ileadall42