4

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'

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
yuqli
  • 4,461
  • 8
  • 26
  • 46

1 Answers1

4

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]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks! This works perfectly for me. Another question is what exactly is a `DatetimeIndex` object? Is it like a Series of Timestamps objects? – yuqli Apr 28 '17 at 10:51
  • Maybe the best is check [this](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#datetimeindex) - it is Index with datetimes. – jezrael Apr 28 '17 at 10:52
  • Thanks. This possibly saves me hours. From your second answer I think the problem is because I do not understand how `index` works in Pandas. Going to check that first! – yuqli Apr 28 '17 at 10:56