Pandas: 无法将类型 <class 'pandas.tseries.index.DatetimeIndex'> 转换为时间戳

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

我在尝试使用标签对 pandas 数据帧进行切片时收到以下错误消息。

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

我很困惑为什么不能使用 datetimeIndex 对象在此处对 pandas 数据帧进行切片,因为根据 truncating 函数的文档,这应该可行?为什么我仍然需要将 datetimeIndex 转换为 Timestamp?

所以我猜我可能错过了这里的一些细节?任何帮助,将不胜感激。谢谢!

这是我的示例数据的代码和输出:

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'

我认为您需要 [0] 才能将 DatetimeIndex 作为具有一个值的数组转换为标量:

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

或更好:

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