Pandas:无法将 <class 'pandas.tseries.index.DatetimeIndex'> 类型转换为时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43678288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: Cannot convert type <class 'pandas.tseries.index.DatetimeIndex'> to Timestamp
提问by yuqli
I got the following error message when trying to slicing a pandas dataframe using labels.
尝试使用标签切片 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(['2010-05-05'], dtype='datetime64[ns]', name=u'Date', freq=None)] 类型转换为时间戳
I am confused why datetimeIndex object cannot be used to slice this pandas dataframe here, because from the documentation on truncatingfunction, this should work? Why do I still need to convert datetimeIndex to Timestamp?
我很困惑为什么不能使用 datetimeIndex 对象在这里切片这个 Pandas 数据帧,因为从截断函数的文档来看,这应该有效吗?为什么我仍然需要将 datetimeIndex 转换为 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'
类'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)
DatetimeIndex(['2010-05-05'], dtype='datetime64[ns]', name=u'Date', freq=None)
type(triggerDate)
class 'pandas.tseries.index.DatetimeIndex'
类'pandas.tseries.index.DatetimeIndex'
type(cutDate)
class 'pandas.tseries.index.DatetimeIndex'
类'pandas.tseries.index.DatetimeIndex'
回答by jezrael
I think yous need [0]
for convert DatetimeIndex
as array with one value to scalar:
我认为您需要[0]
将DatetimeIndex
具有一个值的数组转换为标量:
triggerDate = dat.loc[dat.Close <= threshold[0]][:1].index[0]
Or better:
或更好:
triggerDate = dat.index[dat.Close <= threshold[0]][0]