【问题标题】:Pandas: Cannot convert type <class 'pandas.tseries.index.DatetimeIndex'> to TimestampPandas:无法将类型 <class 'pandas.tseries.index.DatetimeIndex'> 转换为时间戳
【发布时间】:2017-09-26 11:01:17
【问题描述】:

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

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

TypeError:无法将类型的输入 [DatetimeIndex(['2010-05-05'], dtype='datetime64[ns]', name=u'Date', freq=None)] 转换为时间戳

我很困惑为什么不能在这里使用 datetimeIndex 对象来分割这个 pandas 数据帧,因为从 truncating 函数的文档来看,这应该有效吗?为什么我还需要将 datetimeIndex 转换为 Timestamp?

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

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

type(dat)

类'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)

类'pandas.tseries.index.DatetimeIndex'

type(cutDate)

类'pandas.tseries.index.DatetimeIndex'

【问题讨论】:

  • 看来需要[0] - triggerDate = dat.loc[dat.Close &lt;= threshold[0]][:1].index[0]

标签: pandas numpy python-datetime datetimeindex


【解决方案1】:

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

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

或者更好:

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

【讨论】:

  • 谢谢!这对我来说非常有效。另一个问题是DatetimeIndex 对象到底是什么?它像一系列 Timestamps 对象吗?
  • 也许最好的方法是检查this - 它是带有日期时间的索引。
  • 谢谢。这可能会节省我几个小时。从您的第二个回答中,我认为问题在于我不明白 index 在 Pandas 中的工作原理。先检查一下!
猜你喜欢
  • 2020-09-11
  • 2017-06-26
  • 2016-10-30
  • 1970-01-01
  • 2013-02-14
  • 2017-04-25
  • 2020-02-10
  • 1970-01-01
  • 2012-08-19
相关资源
最近更新 更多