Pandas: Cannot convert type <class 'pandas.tseries.index.DatetimeIndex'> to Timestamp

yuqli picture yuqli · Apr 28, 2017 · Viewed 8.5k times · Source

I got the following error message when trying to slicing a pandas dataframe using labels.

triggerDate = dat.loc[dat.Close <= threshold[0]][:1].index
cutDate= triggerDate.shift(1, 'd')
dat.truncate(before=triggerDate, after=cutDate)

TypeError: Cannot convert input [DatetimeIndex(['2010-05-05'], dtype='datetime64[ns]', name=u'Date', freq=None)] of type to Timestamp

I am confused why datetimeIndex object cannot be used to slice this pandas dataframe here, because from the documentation on truncating function, this should work? Why do I still need to convert datetimeIndex to Timestamp?

So I am guessing I probably miss some details here? Any help would be appreciated. Thanks!

And here is the code and output of my sample dat:

type(dat)

class 'pandas.core.frame.DataFrame'

dat.head(5)

             Open   High    Low  Close     Volume  Adj Close  Cash  Position
Date                                                                        
2010-05-03  13.18  13.49  13.18  13.30  106416800  10.747104  11.7    9988.3
2010-05-04  13.07  13.08  12.75  12.85  123207400  10.383480   0.0       0.0
2010-05-05  12.32  12.70  11.59  12.34  198525600   9.971373   0.0       0.0
2010-05-06  12.17  12.51  10.59  11.78  237094700   9.518863   0.0       0.0
2010-05-07  11.95  11.97  10.95  11.51  261066500   9.300689   0.0       0.0

triggerDate

DatetimeIndex(['2010-05-05'], dtype='datetime64[ns]', name=u'Date', freq=None)

type(triggerDate)

class 'pandas.tseries.index.DatetimeIndex'

type(cutDate)

class 'pandas.tseries.index.DatetimeIndex'

Answer

jezrael picture jezrael · Apr 28, 2017

I think yous need [0] for convert DatetimeIndex as array with one value to scalar:

triggerDate = dat.loc[dat.Close <= threshold[0]][:1].index[0]

Or better:

triggerDate = dat.index[dat.Close <= threshold[0]][0]